[cpp] view plaincopy

  1. #include <iostream>  

  2.   

  3. #include <vector>  

  4.   

  5.   

  6. using namespace std;  

  7.   

  8. void main()  

  9.   

  10. {  

  11.   

  12.    vector<int>ivec1(10,42); //内置方法,初始化的内容为10个42  

  13.   

  14.    vector<int>ivec2(10);  

  15.   

  16.    vector<int>::size_type ix=0;  

  17.   

  18.    for(ix;ix<10;++ix)  

  19.   

  20.    {  

  21.   

  22.       ivec2[ix]=42; //下标操作  

  23.   

  24.    }  

  25.   

  26.     vector<int>ivec3(10);  

  27.   

  28.    for(vector<int>::iterator iter=ivec3.begin();iter!=ivec3.end();++iter)  

  29.   

  30.    {  

  31.   

  32.       *iter=42; //迭代器  

  33.   

  34.    }  

  35.   

  36.   

  37.      /////下面两种方法最佳,他们使用标准库定义的操作,无须再定义vector对象时指定容器的大小。比较灵活且不容易出错.  

  38.   

  39.    vector<int>ivec4;  

  40.   

  41.    vector<int>::iterator iter=ivec4.end();  

  42.   

  43.    for(int i=0;i!=10;++i)  

  44.   

  45.    {  

  46.   

  47.       ivec4.insert(iter,42); //在指定位置iter前插入值为的元素,返回指向这个元素的迭代器,   

  48.   

  49.       iter=ivec4.end();  

  50.   

  51.    }  

  52.   

  53.   

  54.   

  55.    vector<int>ivec5;   

  56.   

  57.    vector<int>::size_type cnt=1;  

  58.   

  59.    for(cnt;cnt<=10;++cnt)  

  60.   

  61.    {  

  62.   

  63.       ivec5.push_back(42); //push_back()添加值为的元素到当前vector末尾  

  64.   

  65.    }  

  66.   

  67. }  

  68.    


 

 

以上代码转自http://hi.baidu.com/jiang_yy_jiang/blog/item/5efa4d94d0366e11d31b70ad.html

下面还有一种赋值方法:通过数组指针给vector对象赋值:

如下:


[cpp] view plaincopy

  1. int myarray[5] = {1,3,5,7,9};