引入头文件
#include <vector>
std::vector的简单使用
std::vector实际上是一个类,跟std::string差不多,可以动态调整数组大小(不需要人工输入),这里以int类型举例。
std::vector<int> test;
这时 test就是一个int数组,可以用push_back函数来赋值
test.push_back(1);
test.push_back(2);
test.push_back(3);
输出一下看看
for(int i=0;i<test.size();i++)
std::cout<<test[i]<<std::endl;
当然也可以基于range语法来实现这个for循环
for(const int &i : test)
std::cout<<i<<std::endl;
std::vector的删除
可以用clear函数删除整个数组,也可以用erase来删除指定的数据
test.clear();//删除整个test数组
test.erase(test.begin()+1);//删除数组里第二个数据,在这里就是2
完整代码如下
#include <iostream>
#include <vector>
int main()
{
std::vector<int> test;
test.push_back(1);
test.push_back(2);
test.push_back(3);
//for(int i=0;i<test.size();i++)
// std::cout<<test[i]<<std::endl;
for(const int &i : test)
std::cout<<i<<std::endl;
std::cout<<"*********"<<std::endl;
test.erase(test.begin()+1);
for(const int &i : test)
std::cout<<i<<std::endl;
return 0;
}
std::vector简单优化
由于std::vector动态数组在不知道你数组大小的情况下,会做很多消耗计算机资源的操作,以确保其功能的实现。所以,加入你确定数组的大小,请按照以下操作来初始化你的动态数组。
std::vector<int> test;
test.reserve(3);
test.emplace_back(1);
test.emplace_back(2);
test.emplace_back(3);