比如定义vector<int> v(3)
当我插入pushback4个数据时
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)这样打出来的元素个数有7个之多。谁可以解释下,并给出个正确的用法。
另外,我发现无论定义时定义多少个总是在PUSHBACK的个数在加的,感觉如果这样用,不能用这个方法插入元素一样。
谢谢
当我插入pushback4个数据时
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)这样打出来的元素个数有7个之多。谁可以解释下,并给出个正确的用法。
另外,我发现无论定义时定义多少个总是在PUSHBACK的个数在加的,感觉如果这样用,不能用这个方法插入元素一样。
谢谢
再pushback4就是4个了。
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就是说,它会先初始化插入你所定义个数的元素,所以你的运行情况是正常的
之后你可以v[0]=...修改第一个内容。
定长vector一般用于提高性能,但为了达到这个目的,使用的时候不要超过这个定长。
前三个是0
你在循环里用cout<<*it<<endl; 就能看到结构了
#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;
}