vector的使用频率非常高,因此应该很好的掌握vector。
vector是标准库类型,表示对象的集合,其中所有对象的类型都相同。集合中的每个对象都有一个与之对应的索引,索引用于访问对象。
1、使用vector需要包含的头文件及声明:
#include<vector>
using std::vector;
2、定义和初始化vector对象
vector < T > v1 //v1是一个空的vector,其中元素为T类型,执行默认初始化;
vector < T > v2(v1) //v2中包含v1所有元素的副本(v2=v1);
vector < T > v2 = v1 //同上
vector < T > v3(n, val) //v3中包含n个元素,这n个元素的值均为val;
vector < T > v4(n) //v4中包含n个元素,赋为默认值;
vector < T > v5{a,b,c,……} //v5中包含了初始值个数的元素,每个元素被赋予相应的初始值;
vector < T > v5 = {a,b,c,……} //同上
举例:
vector<int>v1;
vector<int>v2 = v1;
vector<int>v3(3, 4);
vector<int>v4(4);
vector<int>v5{1,2,3,4,5};
vector<int>v6 = { 1,2,3,4,5 };
vector<string>v7{"a","b","c"};
vector<string>v8(10,"abc");
3、向vector添加元素–push_back()
push_back负责把一个值当成vector对象呢的尾元素push到vector对象的尾端。
vector<int>v1;
v1.push_back(1); // 此时v1中只有一个元素,且值为1;
v1.push_back(2); //此时v1中有两个元素,分别为{1,2}
vector<string>v2;
string ct;
while(cin>>ct)
v2.push_back(ct);
4、vector支持的常用操作
v.empty() //判断vector v是否为空
v.size() //返回v中元素个数
v.push_back(t) //向vector v的末尾添加元素t
v = v1; //用同类型v1对v赋值
v == v1; //判断v和v1中的元素是否相同,若完全相同则 = ;
<,<=,>,>= //以字典顺序进行比较元素大小
5、迭代器–begin\end\iterator
begin-负责返回指向第一个元素的迭代器;
end-负责返回指向容器“尾元素的下一个位置”的迭代器;
若容器为空,则begin和end返回的是同一个迭代器;
vector<T>::iterator it; //it能读写vector<T>中的元素;
vector<T>::const_iterator i2; //i2只能读元素,不能写元素;
vector<int>v3{1,2,3,4,5,6};
vector<int>::const_iterator it;
for(it = v3.begin(); it != v3.end(); it++)
{
cout<<*it<<endl;
}
7、查找vector中是否包含某个元素–find
find(起始地址,结束地址,要查找的元素值);
find的返回值为地址;
#include <iostream>
#include<vector>
#include<algorithm> //标准库算法find包含在该头文件中。
using namespace std;
int main()
{
vector<int>v6 = { 1,2,3,4,5 };
auto it = find(v6.begin(),v6.end(),4);
if (it != v6.end())
cout << *it << endl;
else
cout << "do not find it" << endl;
return 0;
}
8、对vector中的元素求和–accumulate
accumulate --包含在头文件 numeric中。
accumulate(起始地址,结束地址,和的初始值);
Attention:和的初始值必须必须与vector中的元素类型一致!!!!!!!!
accumulate返回和;
// hello word.cpp: 定义控制台应用程序的入口点。
#include <iostream>
#include<vector>
#include<numeric>
#include<string>
using namespace std;
int main()
{
vector<int>v6 = { 1,2,3,4,5 };
auto num_v6 = accumulate(v6.begin(),v6.end(),0);
cout << "num_v6 is "<< num_v6 << endl;
vector<string>sh = { "this","is","an","apple" };
auto num_sh = accumulate(sh.begin(),sh.end(),string(""));
//auto num_sh = accumulate(sh.begin(),sh.end(),""); 会报错,因为第三个元素的类型为const string,与vector 中的 string类型不符。
cout << "num_sh is "<< num_sh << endl;
return 0;
}