http://classfoo.com/ccby/article/jnevK
Vector的存储空间是连续的,list不是连续存储的
vector初始化
vector<int>v; //不能使用下标索引赋值,因为还没有空间 vector<int>v1(10, -1);//初始化10个,初值为-1 int a[4] = { 1, 2, 3, 4 }; vector<int>v2(a, a + 4);
如果先定义,后赋值,使用assign
vector<int> foo1(7, 100); vector<int> foo2; vector<int> foo3; vector<int> foo4; //foo1.assign(7, 100); // 填充赋值(1),将7个值为100的整数赋值给foo1 std::vector<int>::iterator it; it = foo1.begin() + 1; foo2.assign(it, foo1.end() - 1); // 范围赋值(2),将foo1中不包括头尾的元素赋值给foo2 int fooarray[] = { 1, 2, 3 }; foo3.assign(fooarray, fooarray + 3); //范围赋值同样适用于数组 foo4.assign({ 1, 9, 8, 13 }); // 初始化列表赋值(3)
添加、删除、插入、清空、交换
vector <int>a; a.push_back(1); //在末尾加一个元素 size+1 a.pop_back(); //删除最后一个元素,size-1
---------------------------------------------------------------------
std::vector<int> foo1(3, 9);
std::vector<int> foo2(3, 9);
std::vector<int> foo3(3, 9);
std::vector<int>::iterator it;
// single element (1)
it = foo1.begin();
foo1.insert(it, 11); // {11,9,9,9}
// fill (2)
it = foo2.begin();
foo2.insert(it, 2, 7); // {7,7,9,9,9}
// range (3)
int fooarray[] = { 1, 2, 3, 4, 5 };
it = foo3.begin();
foo3.insert(it, fooarray + 1, fooarray + 4); // { 2,3,4,9,9,9}
---------------------------------------------------------------------
// 移除第2个元素
foo3.erase(foo3.begin() + 1);//{2,4,9,9,9}
// 移除前三个元素
foo3.erase(foo3.begin(), foo3.begin() + 3);//{9,9}
foo3.clear();//清空
------------------------------------------------
std::vector<int> foo(3, 100);
std::vector<int> bar(5, 200);
foo.swap(bar);
遍历
std::vector<int> foo(5);
std::vector<int>::reverse_iterator rit = foo.rbegin();
int i = 0;
for (rit = foo.rbegin(); rit != foo.rend(); ++rit)
*rit = ++i;
for (unsigned i = 0; i<foo.size(); i++)
std::cout << ' ' << foo[i];
for (std::vector<int>::iterator it = foo.begin(); it != foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << std::endl;