C++ 提高教程 STL Vector互换容器

C++ 提高教程 STL Vector互换容器

# include<iostream>
#include<vector>
# include<algorithm>
# include<string>
using namespace std;

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;
	cout << "交换前:" << endl;
	for (int i = 0; i < 10; i++)
	{
		v1.push_back(i);
	}
	printVector(v1);

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

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


}

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

	v.resize(3);
	cout << "容量大小:" << v.capacity() << endl;
	cout << "v的大小:" << v.size() << endl;

	//巧用swap去收缩
	//vector<int>(v)匿名对象   用v的个数来初始化匿名对象
	vector<int>(v).swap(v);
	cout << "容量大小:" << v.capacity() << endl;
	cout << "v的大小:" << v.size() << endl;


}
int main()
{
	test02();
	system("pause");
	return 0;
}

 

上一篇:排序算法总结v2


下一篇:Nginx设置Https反向代理,指向Docker Gitlab11.3.9 Https服务