vector是一种类模板,它表示对象的集合。当对象个数不定时用vector
包含
vector的使用需要包含适当的头文件:
#include<vector>
using std::vector;
直接初始化
和其他类型初始化方式类似
vector <T> v1
vector <T> v2(v1) //vector<T> v2 = v1
vector <T> v3(n, v1) //vector<T> v3(n)
vector <T> v4{a,b,c,...}//vector <T> v5 = {a,b,c,...}
vector方法
.push_back
向vector的末端加入值
Eg:
#include <iostream>
#include <vector>
int main()
{
// 创建含有整数的 vector
std::vector<int> v = {7, 5, 16, 8};
// 添加二个整数到 vector
v.push_back(25);
v.push_back(13);
// 迭代并打印 vector 的值
for(int n : v) {
std::cout << n << ' ';
}
std::cout << endl;
}
g++ -o out prog_vector.cpp -std=c++11
引用操作
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v_int;
for(int i = 0; i < 10; i++)
{
v_int.push_back(i);
}
for(auto &i: v_int)
{
i *= i;
}
// cout << v_int.size() << endl;
for(int i : v_int)
{
cout << i << ' ';
}
cout << endl;
return 0;
}
迭代器
for(auto i = v_int.begin(); i != v_int.end(); i++)
{
cout << *i << " ";
}
cout << endl;
到这里,可以直接理解vector为C里面用void*写的链表,封装起来方便重写代码,但也增加了开销。
其它
practice 3.17
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
vector<string> v_str;
string str;
while(cin >> str)
{
for(auto &c : str)
c = toupper(c);
v_str.push_back(str);
}
for(auto i : v_str)
cout << i << endl;
return 0;
}
practice 3.20
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> vi;
int i;
while(cin >> i)
{
vi.push_back(i);
}
for(auto b = vi.begin(), e = vi.end()-1,
mid = b + (e-b)/2, j = b; j != mid; j++, e--)
{
cout << (*j) + (*e) << ' ';
}
cout << endl;
return 0;
}
more
更多内容请参考 参考链接
reference
cpp primer
http://zh.cppreference.com/w/cpp/container/vector
http://www.cplusplus.com/reference/vector/vector