现在的位置: 首页 > 综合 > 正文

STL 学习笔记 ( 二. vector )

2012年10月17日 ⁄ 综合 ⁄ 共 1320字 ⁄ 字号 评论关闭

MiYu原创, 转帖请注明 : 转载自 ______________白白の屋    

 

vector

 

一.  vector可以模拟动态数组

 

.  vector的元素可以是任意类型T,但必须具备赋值和拷贝能力(具有public

 

       拷贝构造函数和重载的赋值操作符)

 

    三.必须包含的头文件#include <vector>

 

        四.  vector支持随机存取

 

        五.  vector的大小(size)和容量(capacity)通常是不同的,size返回实际元素个数

 

               capacity返回vector能容纳的元素最大数量如果插入元素时,元素个数超过capacity

 

       需要重新配置内部存储器。 

 

                      

 

->构造、拷贝和析构 

 

 

 

 ->非变动操作

 

 

 eg.

   vector<int> v1(10);
   cout << "The capacity of v1 is " << v1.capacity() << endl;
   cout << "The size of v1 is " << v1.size() << endl;
   vector<int> v2;
   v2.reserve(20);
   cout << "The capacity of v2 is " << v2.capacity() << endl;
   cout << "The size of v2 is " << v2.size() << endl;
output :
   The capacity of v1 is 10
   The size of v1 is 10
   The capacity of v2 is 20
   The size of v2 is 0

 

 

 

 

 

->赋值操作

 

 

 

所有的赋值操作都有可能调用元素类型的默认构造函数,拷贝构造函数,赋值操作符和析构函数

 

如: 

  std::list<T> l;

 

  std::vector<T> v;

 

 

 

  v.assign(l.begin(),l.end());

eg.    

   vector<int> v;
   v.assign( 10, 42 );
   for( vector<int>::size_type i = 0; i < v.size(); i++ ) {
     cout << v[i] << " ";
   }
   cout << endl;

OutPut : 

42 42 42 42 42 42 42 42 42 42

 

   vector<int> v1;
   for( int i = 0; i < 10; i++ ) {
     v1.push_back( i );
   }
 
   vector<int> v2;
   v2.assign( v1.begin(), v1.end() );
 
   for( vector<int>::size_type i = 0; i < v2.size(); i++ ) {
     cout << v2[i] << " ";
   
cout << endl; 

output :

0 1 2 3 4 5 6 7 8 9  

 

 

元素存取 

 

 

 下面的操作是错误的:

      std::vector<T> v;//empty

 


  v[5]= t; //runtime error

 

  std::cout << v.front(); //runtime error

eg. 

  vector<string> words;

    string str;
 
while( cin >> str ) words.push_back(str);
 
sort( words.begin(

抱歉!评论已关闭.