vector用法

目录

vector底层数据结构:

方法:

增加:

删除:

查询:


vector底层数据结构:

动态开辟的数组,通过三个指针_first、_last、_end维护

  • _first指向动态数组的首地址
  • _last指向最后一个有效元素的尾后
  • _end指向动态数组最后一个位置的尾后

size为容器的有效元素,size=_last - _first

_end - _first 为容器当前的最大容量

方法:

增加:

  • push_back(val),尾插,O(1),容量不够时会扩容
  • insert(it,val),在it迭代器指向的位置添加元素,O(n),容量不够时会扩容,返回值为指向该位置的迭代器

删除:

  • pop_back(),尾删,O(1)
  • erase(it),删除迭代器指向位置的元素,O(n),返回值为指向该位置的迭代器

查询:

operator[] , 下标的随机访问 ,O(1)

iterator 迭代器遍历容器

foreach语法糖(通过iterator实现)

注:

对容器进行连续的插入或删除(insert/erase)时,一定要更新迭代器,否则第一次操作后,迭代器就失效了!

常用方法:

size() , empty()
reserve(int); 预留空间,只开空间,不添元素
resize(int); 扩容,即开空间,也添元素

swap() ,两容器进行元素交换

代码练习:

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;

int main()
{
	vector<int> vec;

	vec.reserve(20);
	for (int i = 0; i < 20; i++)
	{
		vec.push_back(rand() % 100);
	}
	for (int i = 0; i < 20; i++)
	{
		cout << vec[i] << " ";
	}
	cout << endl;

	auto it1 = vec.begin();

	while (it1 != vec.end())
	{
		if (*it1 % 2 == 0)
		{
			it1 = vec.erase(it1);
		}
		else
		{
			it1++;
		}
	}

	for (it1=vec.begin(); it1 != vec.end(); it1++)
	{
		cout << *it1 << " ";
	}
	cout << endl;

	int size = vec.size();
	for (it1=vec.begin();it1!=vec.end();it1++)
	{
		if (*it1 % 2 != 0)
		{
			it1 = vec.insert(it1, *it1 - 1);
			it1++;
		}
	}

	for (auto x : vec)
	{
		cout << x << " ";
	}
	cout << endl;
	vector<int> tmp(12);
	for (auto& x : tmp)
	{
		x = 12;
	}
	for (auto& x : tmp)
	{
		cout << x << " ";
	}
	swap(vec, tmp);
	cout << endl;
	for (auto& x : tmp)
	{
		cout << x << " ";
	}
	return 0;
}
相关推荐
凤年徐6 分钟前
【C/C++】深入理解指针(二)
c语言·开发语言·c++·经验分享·笔记·指针
Hello-FPGA14 分钟前
QT 初体验
开发语言·qt
Cao12345678932139 分钟前
扫雷-C语言版
c语言·开发语言
天堂的恶魔9461 小时前
QT —— 信号和槽(槽函数)
开发语言·qt
水w1 小时前
【Python爬虫】详细入门指南
开发语言·爬虫·python·scrapy·beautifulsoup
weixin_445054721 小时前
力扣刷题-热题100题-第35题(c++、python)
c++·python·leetcode
XXYBMOOO1 小时前
基于 Qt 的 BMP 图像数据存取至 SQLite 数据库的实现
数据库·c++·qt
Susea&2 小时前
数据结构初阶:双向链表
c语言·开发语言·数据结构
虾球xz2 小时前
游戏引擎学习第230天
c++·学习·游戏引擎
pianmian12 小时前
arcgis几何与游标(1)
开发语言·python