注册 登录
编程论坛 C++教室

下面的一段代码是为了验证insert对deque和vector的影响,可是出来的结果让我不是很理解,求解释!

纯黑色 发布于 2014-01-25 12:59, 687 次点击
程序代码:

#include <vector>
#include <deque>
#include <iostream>
using namespace std;

int main ()
{


        char str[] = "fuckyou";
        vector<char> v1(&str[0],&str[sizeof(str)]);
        deque<char> q1(&str[0],&str[sizeof(str)]);

        vector <char>::iterator vitr=v1.begin();
        cout<<*(vitr)<<endl;
        v1.insert(v1.begin()+2,'a');
        cout<<*(vitr)<<endl;//我不明白这一行的输出结果,求解释。

        cout<<"-----------------------"<<endl;
        deque <char>::iterator qitr=q1.begin();
        cout<<*(qitr)<<endl;
        q1.insert(q1.begin()+2,'a');
        cout<<*(qitr)<<endl;
        return 0;
}

编译环境:centos g++

结果:
f
(空)//这块为什么不输出?
-----------------------
f
u
4 回复
#2
玩出来的代码2014-01-25 14:01
vector::insert
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call.
#3
纯黑色2014-01-25 16:17
回复 2楼 玩出来的代码
就是说在这个例子中,vector reallocate了 对吗?
#4
rjsp2014-01-25 16:26
//v1.reserve( 20 ); 加上这一句可以确保不发生reallocation
        vector <char>::iterator vitr=v1.begin();
        cout<<*(vitr)<<endl;
size_t s1 = v1.capacity();
        v1.insert(v1.begin()+2,'a');
size_t s2 = v1.capacity();
if( s2 != s1 ) cout << "reallocated" << endl; 通过判断前后的capacity()才判断是否reallocate了
#5
玩出来的代码2014-01-25 17:37
这个例子不管有没有reallocate, 你的使用方法都与insert的本意表现不一致。

This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
1