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;
}
相关推荐
肆忆_20 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc