vector容器(二)

一、vector数据存取

函数原型:

cpp 复制代码
at(int idx); //返回索引idx所指的数据
operator[]; //返回索引idx所指的数据
front(); //返回容器中第一个数据元素
back(); //返回容器中最后一个数据元素

代码示例:

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

//vector容器数据存取
void test()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}

	//利用[]方式访问数组中的元素
	for (int i = 0; i < v1.size(); i++)
	{
		cout << v1[i] << " ";
	}
	cout << endl;

	//利用at方式访问元素
	for (int i = 0; i < v1.size(); i++)
	{
		cout << v1.at(i) << " ";
	}
	cout << endl;

	//获取第一个元素
	cout << "第一个元素为:" << v1.front() << endl;

	//获取最后一个元素
	cout << "最后一个元素为:" << v1.back() << endl;
}

int main()
{
	test();
	return 0;
}

总结:除了用迭代器获取vector容器中元素,[ ]和at也可以

二、vector互换容器:

函数原型:

cpp 复制代码
swap(vec); // 将vec与本身的元素互换

代码示例:

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

//vector容器互换
void printVector(vector<int> &v)
{
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}

void test01()
{
	vector<int>v1;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	cout << "交换前:" << endl;
	printVector(v1);

	vector<int>v2;
	for (int i = 10; i >0; i--)
	{
		v2.push_back(i);
	}
	printVector(v2);

	cout << "交换后:" << endl;
	v1.swap(v2);
	printVector(v1);
	printVector(v2);
}

//实际用途
//巧用swap可以收缩内存空间
void test02()
{
	vector<int>v;
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(i);
	}
	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;

	v.resize(3);//重新指定大小
	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;

	//巧用swap收缩内存
	vector<int>(v).swap(v);
	//vector<int>(v)匿名对象
	cout << "v的容量为:" << v.capacity() << endl;
	cout << "v的大小为:" << v.size() << endl;
}

int main()
{
	//test01();
	test02();
	return 0;
}

**三、vector预留空间:**减少vector在动态扩展容量时的扩展次数

函数原型:

cpp 复制代码
reserve(int len); //容器预留len个元素长度,预留位置不初始化,元素不可访问。

代码示例:

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

//vector容器 预留空间
void test()
{
	vector<int>v;
	//利用reserve预留空间
	v.reserve(100000);

	int num = 0;//统计开辟次数
	int* p = NULL;
	for (int i = 0; i < 100000; i++)
	{
		v.push_back(i);
		if (p != &v[0])
		{
			p = &v[0];
			num++;
		}
	}
	cout << "num = " << num << endl;//预留前开辟30次,预留后一次
}

int main()
{
	test();
	return 0;
}

总结:如果数据量较大,可以一开始利用reserve预留空间

相关推荐
CYRUS_STUDIO2 分钟前
如何防止 so 文件被轻松逆向?精准控制符号导出 + JNI 动态注册
android·c++·安全
℃CCCC2 分钟前
请求库-axios
开发语言·华为·网络请求·harmonyos·deveco studio·axios请求·arkts编程
CYRUS_STUDIO3 分钟前
C&C++ 代码安全再升级:用 OLLVM 给 so 加上字符串加密保护
c++·安全·llvm
ling__i8 分钟前
java day18
java·开发语言
矛取矛求8 分钟前
日期类的实现
开发语言·c++·算法
大翻哥哥19 分钟前
Python 2025:AI工程化与智能代理开发实战
开发语言·人工智能·python
会开花的二叉树36 分钟前
彻底搞懂 Linux 基础 IO:从文件操作到缓冲区,打通底层逻辑
linux·服务器·c++·后端
在下雨59938 分钟前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
再努力"亿"点点41 分钟前
Sklearn(机器学习)实战:鸢尾花数据集处理技巧
开发语言·python
清朝牢弟43 分钟前
Win系统下配置PCL库第一步之下载Visual Studio和Qt 5.15.2(超详细)
c++·qt·visual studio