c++ vector 初始化

来源:互联网 发布:淘宝网卫衣女款 编辑:程序博客网 时间:2024/06/12 00:35

2011-01-26 12:16:08|  分类: c++|举报|字号 订阅

/*
* vector 初始化
*/


#include <vector>
#include <list>
#include <string>
#include <iostream>
using namespace std;

void main()
{
 vector<int>::iterator int_ite;
 vector<string>::iterator string_ite;

 //vector<T> v(n,i)形式,v包含n 个值为 i 的元素
 vector<int> ivec(10,0);
 for(int_ite=ivec.begin ();int_ite!=ivec.end ();int_ite++)
  cout<<"ivec: "<<*int_ite<<endl;

 //vector<T> v(v1)形式,v是v1 的一个副本
 vector<int> ivec1(ivec);
 for(int_ite=ivec1.begin ();int_ite!=ivec1.end ();int_ite++)
  cout<<"ivec1: "<<*int_ite<<endl;

 //vector<T> v(n)形式,v包含n 个值初始化的元素
 vector<int> ivec2(10);
 for(int_ite=ivec2.begin ();int_ite!=ivec2.end ();int_ite++)
  cout<<"ivec2: "<<*int_ite<<endl;

 //vector<T> v(n)形式,v包含n 个值初始化的元素
 vector<string> svec(10);
 for(string_ite=svec.begin ();string_ite!=svec.end ();string_ite++)
  cout<<"svec: "<<*string_ite<<endl;

 //数组初始化vector
 int iarray[]={1,2,3,4,5,6,7,8,9,0};
 //count: iarray数组个数
 size_t count=sizeof(iarray)/sizeof(int);
 //int数组初始化 ivec3 
 vector<int> ivec3(iarray,iarray+count);
 for(int_ite=ivec3.begin ();int_ite!=ivec3.end ();int_ite++)
  cout<<"ivec3: "<<*int_ite<<endl;

 //string数组初始化 svec1
 string word[]={"ab","bc","cd","de","ef","fe"};
 //s_count: word数组个数
 size_t s_count=sizeof(word)/sizeof(string);
 //string数组初始化 svec1 
 vector<string> svec1(word,word+s_count);
 for(string_ite=svec1.begin ();string_ite!=svec1.end ();string_ite++)
  cout<<"svec1: "<<*string_ite<<endl;

 

//用 back_inserter 函数
 vector<int> ivec4;  //空对象
 fill_n(back_inserter(ivec4),10,3);  //10个3 填充ivec4.
 for(int_ite=ivec4.begin ();int_ite!=ivec4.end ();int_ite++)
  cout<<"ivec4: "<<*int_ite<<endl;

}

0 0