比如定义vector<int> v(3)
当我插入pushback4个数据时
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)这样打出来的元素个数有7个之多。谁可以解释下,并给出个正确的用法。
另外,我发现无论定义时定义多少个总是在PUSHBACK的个数在加的,感觉如果这样用,不能用这个方法插入元素一样。
谢谢

解决方案 »

  1.   

    vector<int> v;
    再pushback4就是4个了。
      

  2.   

    explicit vector(
       size_type _Count
    );_Count
    The number of elements in the constructed vector.// Create a vector v1 with 3 elements of default value 0
       vector <int> v1( 3 );下面是MSDN上的例子
    cout << "v1 =" ;
       for ( v1_Iter = v1.begin( ) ; v1_Iter != v1.end( ) ; v1_Iter++ )
          cout << " " << *v1_Iter;
       cout << endl;
    输出
    v1 = 0 0 0就是说,它会先初始化插入你所定义个数的元素,所以你的运行情况是正常的
      

  3.   

    vector<int> v(3)
    之后你可以v[0]=...修改第一个内容。
      

  4.   

    vector用于连续内存,当你vector<int> v(3)时,它只申请3个元素元素的空间,当你再push一个进去的时候,它会根据一定的策略重新申请内存,然后再将原来三个元素复制过去,将原来的内存释放掉,这个时候原来的iterator当然也会全部失效,你可以想像到有多伤性能。
    定长vector一般用于提高性能,但为了达到这个目的,使用的时候不要超过这个定长。
      

  5.   

    你先分配了3个为0的元素, 然后又push_back() 4个元素 总共7个元素 
    前三个是0
    你在循环里用cout<<*it<<endl; 就能看到结构了
      

  6.   


    #include<iostream>
    #include<vector>
    using namespace std;
    int main()
    {
    vector<int> ivec(3);// 相当于ivec(3,0) 
    int val;
    while(cin>>val)//ctrl+z结束
    {
    ivec.push(val);//这个是在前面三个基础上增加元素. vector不需要提前定义有多少个元素。所以叫他可变长数组
    }
    vector<int>::iterator it=ivec.begin();
    for(;it!=ivec.end();++it)
    cout<<*it<<endl;
    return 0;
    }