【C++初阶】vector(上)

本文中的string类的常用接口可以查询相关的文档进行查看:文档查询

目录

1,vector的遍历

2,其他容器迭代器初始化,只要数据类型可以匹配上

3,rbegin  &  rend

4,reverse & resize

5,assign

6,insert 

7,sort

8,erase


1,vector的遍历

void test_vector1()
{
	vectorv;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	v.push_back(4);
	v.push_back(5);
	//下标+[]
	for (size_t i = 0; i < v.size(); i++)
	{
		//v[i] -= 1;
		cout << v[i] << " ";
	}
	cout << endl;
	//迭代器
	vector::iterator it = v.begin();
	while (it != v.end())
	{
		*it += 1;
		cout << *it << " ";
		it++;
	}
	cout << endl;
	//范围for
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
}
int main()
{
	test_vector1();
	return 0;
}

2,其他容器迭代器初始化,只要数据类型可以匹配上

(*iterator 对象的类型跟vector中存的数据类型是一致的)

void test_vector2()
{
	string s("hello world");
	vectorv(s.begin(), s.end());
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
}

3,rbegin  &  rend

【C++初阶】vector(上)_第1张图片

vector::reverse_iterator rit = v.rbegin();
	while (rit != v.rend())
	{
		cout << *rit << " ";
		rit++;
	}
	cout << endl;

4,reverse & resize

void test_vector4()
{
	vectorv;
	//cout << v.max_size() << endl;
	v.reserve(10);//开空间,改变容量
	//下面这样的用法是错误的——>operator[]中回去检查i是否小于size
	//for (size_t i = 0; i < 10; i++)
	//{
	//	v[i] = i;//assert(i<_size)
	//}
	for (size_t i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	v.resize(20, 1);//开空间+初始化
	for (size_t i = 0; i < 20; i++)
	{
		v[i] = i;
	}
}

5,assign

void test_vector5()
{
	int a[] = { 1, 2, 3, 4, 5 };
	vectorv;
	//[first,last)
	v.assign(a, a + 4);
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
}

【C++初阶】vector(上)_第2张图片

6,insert 

void test_vector6()
{
	int a[] = { 1, 2, 3, 4, 5 };
	vectorv(a, a + 5);
	//头插
	v.insert(v.begin(), 0);
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
}

假设想在2的前面插入呢?

vector::iterator pos = find(v.begin(), v.end(), 2);
	if (pos != v.end())
	{
		v.insert(pos, 20);
	}
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;

7,sort

//默认排升序
	sort(v.begin(), v.end());
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
	//排降序—关于greater是一个仿函数
	sort(v.begin(), v.end(), greater());
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;

8,erase

//头删
	v.erase(v.begin());
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;
	//删除pos位置的数
	vector::iterator pos = find(v.begin(), v.end(), 2);
	if (pos != v.end())
	{
		v.erase(pos);
	}
	for (auto e : v)
	{
		cout << e << " ";
	}
	cout << endl;

你可能感兴趣的:(c++,开发语言,后端)