代码拉取完成,页面将自动刷新
#include<iostream>
#include<vector>
using namespace std;
#include<string>
void test_vector1()
{
vector<int> v1;
vector<int> v2(10, 0); //开辟10个整型的空间,并将每个空间初始化为0
for (auto i : v2)
{
cout << i << " ";
}
cout << endl;
string s("hello world");
vector<int> v3(s.begin(), s.end()); //用迭代器区间来初始化v3
vector<int>::iterator it = v3.begin();
while (it != v3.end())
{
cout << *it << " ";
++it;
}
cout << endl;
}
void test_vector2()
{
vector<int> v;
size_t sz = v.capacity();
cout << "mark v grow:" << endl;
for (int i = 0; i < 100; i++)
{
v.push_back(i);
if (sz != v.capacity())
{
sz = v.capacity();
cout << "capcaity changed:" << sz << endl;
}
}
//大概是1.5倍扩容
}
void test_vector3()
{
vector<int> v;
//v.reserve(100); //仅仅只是将capacity开辟为100,但是size还是为0
v.resize(100); //size变为100,capacity也开辟为100(或100以上)
for (size_t i = 0; i < 100; i++)
{
v[i] = i;
}
//注意:上面如果是用reserve来扩容,虽然有容量,但是不能通过v[i]这种形式给数组赋值
//因为[]重载里面有assert断言size不能为0,所以即使开辟了空间,也是不能通过[]去给数组赋值的
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
}
void test_vector4()
{
vector<int> v;
//max_size()的作用是返回容器在理论上或实现上能容纳的最大元素数量
cout << v.max_size() << endl;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
cout << v.size() << endl;
cout << v.capacity() << endl;
cout << "-------------------------" << endl;
//reserve会将capacity扩容为跟所给参数一样大,但是不会改变size
//注意;如果所给参数小于当前的size时,capacity会改变成跟size一样大
v.reserve(100);
cout << v.size() << endl;
cout << v.capacity() << endl;
cout << "-------------------------" << endl;
//将size调整为跟所给参数一样大,但是不改变空间容量capacity
v.resize(3);
cout << v.size() << endl;
cout << v.capacity() << endl;
cout << "-------------------------" << endl;
//当容器元素数量size远小于其预分配容量capacity时,
//调用shrink_to_fit()会尝试将capacity降低至与size相等,释放多余的内存空间
v.shrink_to_fit();
cout << v.size() << endl;
cout << v.capacity() << endl;
}
void test_vector5()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.insert(v.begin(), 0);
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
auto it1 = find(v.begin(), v.end(), 3);
if (it1 != v.end())
{
v.insert(it1, 30); //注意:it1这个迭代器在insert使用以后会失效
}
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
auto it2 = find(v.begin(), v.end(), 3);
if (it2 != v.end())
{
v.erase(it2); //注意:it2这个迭代器在erase后会失效
}
for (auto e : v)
{
cout << e << " ";
}
cout << endl;
cout << v.size() << endl;
cout << v.capacity() << endl;
v.clear(); //clear是用来清理掉有效数据的,但是不会释放空间capacity
cout << v.size() << endl;
cout << v.capacity() << endl;
}
int main()
{
test_vector1();
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。