sentence.push_back("how ");
sentence.push_back("are ");
sentence.push_back("you ");
sentence.push_back(" ");
copy(sentence.begin(),sentence.end(),
ostream_iterator
cout << endl;
sentence.assign(3,"new");
copy(sentence.begin(),sentence.end(),
ostream_iterator
cout << endl;
}
#include
#include
#include
#include
using namespace std;
int main()
{
vector
cout << "max_size():" << sentence.max_size() << endl;
cout << "size():" << sentence.size() << endl;
cout << "capacity():" << sentence.capacity() << endl;
sentence.reserve(5);
sentence.push_back("Hello,");
sentence.push_back("how ");
sentence.push_back("are ");
sentence.push_back("you ");
sentence.push_back(" ");
copy(sentence.begin(),sentence.end(),
ostream_iterator
cout << endl;
sentence.assign(3,"new");
copy(sentence.begin(),sentence.end(),
ostream_iterator
cout << endl;
}运行结果:

可以看出原来的元素全部被删除了。
元素存取

在这几个函数中,唯一进行下标检查的是at函数。
因此,在调用operator[]的时候,必须心理清楚索引是否是有效的。
迭代器相关函数

迭代器失效的两种情况是:
1、在一个较小的位置上删除或者是移动元素。
2、由于容量的变换引起内存重新分配。
插入和移除元素

插入和移除元素,都会使“作用点”之后的各元素的reference、pointers、iterators失效。插入操作还可能引发内存重新分配,那么该容器上的所有的reference、pointers、iterators都会失效。
四、把vector当做一般数组使用
现在的C++标准保证vector的元素必须分布于连续空间中。对于vector中的一个合法索引,满足下列表达式:
&v[i] = &v[0] + i;
我们必须保证vector能够容纳所有数据。如果使用的是C-String,记住最后有个'\0'。
只要我们需要一个元素型别为T的数组,就可以采用vector
注意:千万不要把迭代器当做第一元素的地址来传递。因为vector迭代器是由实作版本定义的,不一定是一个一般指针。
[cpp]
printf("%s",v.begin());//ERROR(might work,but not portable)
printf("%s",&v[0]);//OK
printf("%s",v.begin());//ERROR(might work,but not portable)
printf("%s",&v[0]);//OK
摘自 江南烟雨