STL vector and list

转载自:http://blog.csdn.net/xiaoding133/article/details/11826245

STL 描述:

C++标准模块库是一个提供了公共编程数据结构和函数的模板类集合,如双连接表(list),配对数组(map),可扩展数组(vector),大串的存储操作(rope)等。STL库可以从http://www.sgi.com/tech/stl/ 获取。

 

STL可以分为以下几类:

  • 容器类:
    • 顺序容器:
      • vector:动态数组变量,结构体或对象。可以插入在末尾插入数据,支持快速随机访问。
      • deque: 支持在数组的前面和后面插入元素,双端队列。
      • list: 基于链表的变量、结构或对象。可以在任何地方插入和删除元素。支持快速插入、删除。
    • 关联容器:
      • set (不允许有重复元素在set中), multiset (可以有重复元素): 平衡二叉树结构有序的数据的集合,能快速搜索。
      • map (唯一keys), multimap (允许重复keys): 关联键 - 值对的平衡二叉树结构。
    • 容器适配器:
      • stack LIFO 栈
      • queue FIFO 队列
      • priority_queue 返回最高优先级的元素,优先级队列
    • 字符串:
      • string:字符串及其操作
      • rope: 字符串存储和操作
    • bitset: 直观的存储位和操作位。
  • 泛型算法:
    • 迭代器iterator: 代表容器中的位置,一个迭代器定义为一个容器类类型。
    • 算法algorithm: 提供查找,计数,搜索容器中的元素的类。
    • 智能指针auto_ptr: 关联内存指针避免内存泄露的类。

STL vector:

   初始化:
      vector<int> ivec;
      vector<int > vec2(ivec);
     vector c (iter.begin,iter.end);
      vecotr<int > c(5,0);
       vector<int> c(5);
 
         example 1: 用vector存储STL strings,并且用三种方法类访问vector中的元素:
  1. #include <iostream>  
  2. #include <vector>  
  3. #include <string>  
  4.   
  5. using namespace std;  
  6.   
  7. main()  
  8. {  
  9.    vector<string> SS;  
  10.   
  11.    SS.push_back("The number is 10");  
  12.    SS.push_back("The number is 20");  
  13.    SS.push_back("The number is 30");  
  14.   
  15.    cout << "Loop by index:" << endl;  
  16.   
  17.    int ii;  
  18.    for(ii=0; ii < SS.size(); ii++) //第一种方法访问  
  19.    {  
  20.       cout << SS[ii] << endl;  
  21.    }  
  22.   
  23.    cout << endl << "Constant Iterator:" << endl;  
  24.   
  25.    vector<string>::const_iterator cii;  
  26.    for(cii=SS.begin(); cii!=SS.end(); cii++)//第二种方法  
  27.    {  
  28.       cout << *cii << endl;  
  29.    }  
  30.   
  31.    cout << endl << "Reverse Iterator:" << endl;  
  32.   
  33.    vector<string>::reverse_iterator rii;  
  34.    for(rii=SS.rbegin(); rii!=SS.rend(); ++rii)// 第三种方法  
  35.    {  
  36.       cout << *rii << endl;  
  37.    }  
  38.   
  39.    cout << endl << "Sample Output:" << endl;  
  40.   
  41.    cout << SS.size() << endl;  
  42.    cout << SS[2] << endl;  
  43.   
  44.    swap(SS[0], SS[2]);  
  45.    cout << SS[2] << endl;  
  46. }  
  47.                   
#include <iostream>
#include <vector>
#include <string>

using namespace std;

main()
{
   vector<string> SS;

   SS.push_back("The number is 10");
   SS.push_back("The number is 20");
   SS.push_back("The number is 30");

   cout << "Loop by index:" << endl;

   int ii;
   for(ii=0; ii < SS.size(); ii++) //第一种方法访问
   {
      cout << SS[ii] << endl;
   }

   cout << endl << "Constant Iterator:" << endl;

   vector<string>::const_iterator cii;
   for(cii=SS.begin(); cii!=SS.end(); cii++)//第二种方法
   {
      cout << *cii << endl;
   }

   cout << endl << "Reverse Iterator:" << endl;

   vector<string>::reverse_iterator rii;
   for(rii=SS.rbegin(); rii!=SS.rend(); ++rii)// 第三种方法
   {
      cout << *rii << endl;
   }

   cout << endl << "Sample Output:" << endl;

   cout << SS.size() << endl;
   cout << SS[2] << endl;

   swap(SS[0], SS[2]);
   cout << SS[2] << endl;
}
                

用vector来表示二维、三维数组:

一个二维数组是两个vector,vector构造函数可以初始化的数组的长度,并设置初始值。
example 2:vector二维数组
  1. #include <iostream>  
  2. #include <vector>  
  3.   
  4. using namespace std;  
  5.   
  6. main()  
  7. {  
  8.    // 声明二维数组的大型并且初始化  
  9.    vector< vector<int> > vI2Matrix(3, vector<int>(2,0));      
  10.   
  11.    vI2Matrix[0][0] = 0;  
  12.    vI2Matrix[0][1] = 1;  
  13.    vI2Matrix[1][0] = 10;  
  14.    vI2Matrix[1][1] = 11;  
  15.    vI2Matrix[2][0] = 20;  
  16.    vI2Matrix[2][1] = 21;  
  17.   
  18.    cout << "Loop by index:" << endl;  
  19.   
  20.    int ii, jj;  
  21.    for(ii=0; ii < 3; ii++)  
  22.    {  
  23.       for(jj=0; jj < 2; jj++)  
  24.       {  
  25.          cout << vI2Matrix[ii][jj] << endl;  
  26.       }  
  27.    }  
  28. }  
  29.                   
#include <iostream>
#include <vector>

using namespace std;

main()
{
   // 声明二维数组的大型并且初始化
   vector< vector<int> > vI2Matrix(3, vector<int>(2,0));    

   vI2Matrix[0][0] = 0;
   vI2Matrix[0][1] = 1;
   vI2Matrix[1][0] = 10;
   vI2Matrix[1][1] = 11;
   vI2Matrix[2][0] = 20;
   vI2Matrix[2][1] = 21;

   cout << "Loop by index:" << endl;

   int ii, jj;
   for(ii=0; ii < 3; ii++)
   {
      for(jj=0; jj < 2; jj++)
      {
         cout << vI2Matrix[ii][jj] << endl;
      }
   }
}
                
example 3vector三维数组
     
  1. #include <iostream>  
  2. #include <vector>  
  3.   
  4. using namespace std;  
  5.   
  6. main()  
  7. {  
  8.                                // Vector length of 3 initialized to 0  
  9.    vector<int> vI1Matrix(3,0);  
  10.   
  11.                                // Vector length of 4 initialized to hold another   
  12.   
  13.                                // vector vI1Matrix which has been initialized to 0  
  14.    vector< vector<int> > vI2Matrix(4, vI1Matrix);  
  15.   
  16.                                // Vector of length 5 containing two dimensional vectors  
  17.    vector< vector< vector<int> > > vI3Matrix(5, vI2Matrix);  
  18.   
  19.    ...  
#include <iostream>
#include <vector>

using namespace std;

main()
{
                               // Vector length of 3 initialized to 0
   vector<int> vI1Matrix(3,0);

                               // Vector length of 4 initialized to hold another 

                               // vector vI1Matrix which has been initialized to 0
   vector< vector<int> > vI2Matrix(4, vI1Matrix);

                               // Vector of length 5 containing two dimensional vectors
   vector< vector< vector<int> > > vI3Matrix(5, vI2Matrix);

   ...

或者在一条语句中定义:

  1. #include <iostream>  
  2. #include <vector>  
  3.   
  4. using namespace std;  
  5.   
  6. main()  
  7. {  
  8.    vector< vector< vector<int> > > vI3Matrix(2, vector< vector<int> > (3, vector<int>(4,0)) );  
  9.   
  10.    for(int kk=0; kk<4; kk++)  
  11.    {  
  12.       for(int jj=0; jj<3; jj++)  
  13.       {  
  14.          for(int ii=0; ii<2; ii++)  
  15.          {  
  16.             cout << vI3Matrix[ii][jj][kk] << endl;  
  17.          }  
  18.       }  
  19.    }  
  20. }  
#include <iostream>
#include <vector>

using namespace std;

main()
{
   vector< vector< vector<int> > > vI3Matrix(2, vector< vector<int> > (3, vector<int>(4,0)) );

   for(int kk=0; kk<4; kk++)
   {
      for(int jj=0; jj<3; jj++)
      {
         for(int ii=0; ii<2; ii++)
         {
            cout << vI3Matrix[ii][jj][kk] << endl;
         }
      }
   }
}
使用迭代器:
    example 4:  对二维vector使用迭代器
   
  1. #include <iostream>  
  2. #include <vector>  
  3.   
  4. using namespace std;  
  5.   
  6. main()  
  7. {  
  8.    vector< vector<int> > vI2Matrix;    // 声明二维数组  
  9.    vector<int> A, B;  
  10.    vector< vector<int> >::iterator iter_ii;  
  11.    vector<int>::iterator   iter_jj;  
  12.   
  13.    A.push_back(10);  
  14.    A.push_back(20);  
  15.    A.push_back(30);  
  16.    B.push_back(100);  
  17.    B.push_back(200);  
  18.    B.push_back(300);  
  19.   
  20.    vI2Matrix.push_back(A);  
  21.    vI2Matrix.push_back(B);  
  22.   
  23.    cout << endl << "Using Iterator:" << endl;  
  24.   
  25.    for(iter_ii=vI2Matrix.begin(); iter_ii!=vI2Matrix.end(); iter_ii++)  
  26.    {  
  27.       for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++)  
  28.       {  
  29.          cout << *iter_jj << endl;  
  30.       }  
  31.    }  
  32. }  
  33.                   
#include <iostream>
#include <vector>

using namespace std;

main()
{
   vector< vector<int> > vI2Matrix;    // 声明二维数组
   vector<int> A, B;
   vector< vector<int> >::iterator iter_ii;
   vector<int>::iterator   iter_jj;

   A.push_back(10);
   A.push_back(20);
   A.push_back(30);
   B.push_back(100);
   B.push_back(200);
   B.push_back(300);

   vI2Matrix.push_back(A);
   vI2Matrix.push_back(B);

   cout << endl << "Using Iterator:" << endl;

   for(iter_ii=vI2Matrix.begin(); iter_ii!=vI2Matrix.end(); iter_ii++)
   {
      for(iter_jj=(*iter_ii).begin(); iter_jj!=(*iter_ii).end(); iter_jj++)
      {
         cout << *iter_jj << endl;
      }
   }
}
                

构造函数/声明:

 

方法/操作描述
vector<T> v; 声明一个数据类型为 "T"的vector变量v.
vector<T> v(size_type n); 声明一个大小为n,包含数据类型T的vector变量
vector<T> v(size_type n,const T& t); 声明一个大小为n,包含数据类型为T,元素的值为t的vector变量 Declaration: vector(size_type n, const T& t)
vector<T> v(begin_iterator,end_iterator); 从迭代器开始位置到结束位置拷贝一个vector Declaration: template vector(InputIterator, InputIterator)

 

Size 方法/操作: 

Method/operatorDescription
empty() Returns bool (true/false). True if empty. Declaration: bool empty() const
size() Number of elements of vector. Declaration: size_type size() const
resize(n, t=T()) Adjust by adding or deleting elements of vector so that its size is "n". Declaration: void resize(n, t = T())
capacity() Max number of elements of vector before reallocation. Declaration: size_type capacity() const
reserve(size_t n) Max number of elements of vector set to "n" before reallocation. Declaration: void reserve(size_t)
max_size() Max number of elements of vector possible. Declaration: size_type max_size() const
  
其他方法和操作:
 
Method/operatorDescription
erase() clear() Erase all elements of vector. Declaration: void clear()
erase(iterator) erase(begin_iterator,end_iterator) Erase element of vector. Returns iterator to next element. Erase element range of vector. Returns iterator to next element. Declarations:
  • iterator erase(iterator pos)
  • iterator erase(iterator first, iterator last)
= Example: X=Y() Assign/copy entire contents of one vector into another. Declaration: vector& operator=(const vector&)
< Comparison of one vector to another. Declaration: bool operator<(const vector&, const vector&)
== Returns bool. True if every element is equal. Declaration: bool operator==(const vector&, const vector&)
at(index) v[index] Element of vector. Left and Right value assignment: v.at(i)=e; and e=v.at(i); Declaration: reference operator[](size_type n)
front() v[0] First element of vector. (Left and Right value assignment.) Declaration: reference front()
back() Last element of vector. (Left and Right value assignment.) Declaration: reference back()
push_back(const T& value) Add element to end of vector. Declaration: void push_back(const T&)
pop_back() Remove element from end of vector. Declaration: void pop_back()
assign(size_type n,const T& t) Assign first n elements a value "t".
assign(begin_iterator,end_iterator) Replace data in range defined by iterators. Declaration:
insert(iterator, const T& t) Insert at element "iterator", element of value "t". Declaration: iterator insert(iterator pos, const T& x)
insert(iterator pos, size_type n, const T& x) Starting before element "pos", insert first n elements of value "x". Declaration: void insert(iterator pos, size_type n, const T& x)
insert(iterator pos, begin_iterator,end_iterator) Starting before element "pos", insert range begin_iterator to end_iterator. Declaration: void insert(iterator pos, InputIterator f, InputIterator l)
swap(vector& v2) Swap contents of two vectors. Declaration: void swap(vector&)
迭代器方法/操作
Method/operatorDescription
begin() Return iterator to first element of vector. Declaration: const_iterator begin() const
end() Return iterator to end of vector (not last element of vector but past last element) Declaration: const_iterator end() const
rbegin() Return iterator to first element of vector (reverse order). Declaration: const_reverse_iterator rbegin() const
rend() Return iterator to end of vector (not last element but past last element) (reverse order). Declaration: const_reverse_iterator rend() const
++ Increment iterator.
-- Decrement iterator.

STL list:

 

两个例子:

  1. 第一个为数据类型为int
  2. 第二个为类实例
example 1:
  1. // Standard Template Library example  
  2.   
  3. #include <iostream>  
  4. #include <list>  
  5. using namespace std;  
  6.   
  7.   
  8.   
  9. main()  
  10. {  
  11.    list<int> L;  
  12.    L.push_back(0);              // Insert a new element at the end  
  13.    L.push_front(0);             // Insert a new element at the beginning  
  14.    L.insert(++L.begin(),2);     // Insert "2" before position of first argument  
  15.                                 // (Place before second argument)  
  16.    L.push_back(5);  
  17.    L.push_back(6);  
  18.   
  19.    list<int>::iterator i;  
  20.   
  21.    for(i=L.begin(); i != L.end(); ++i) cout << *i << " ";  
  22.    cout << endl;  
  23.    return 0;  
  24. }  
// Standard Template Library example

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



main()
{
   list<int> L;
   L.push_back(0);              // Insert a new element at the end
   L.push_front(0);             // Insert a new element at the beginning
   L.insert(++L.begin(),2);     // Insert "2" before position of first argument
                                // (Place before second argument)
   L.push_back(5);
   L.push_back(6);

   list<int>::iterator i;

   for(i=L.begin(); i != L.end(); ++i) cout << *i << " ";
   cout << endl;
   return 0;
}

 
example 2:
     如果使用自定义类型,需要包括以下几个方面:
     a. 复制构造函数      b.赋值运算符(=)重载
     c.小于运算符重载<
     d.等于运算符==重载
  1. #include <iostream>  
  2. #include <list>  
  3. using namespace std;  
  4.   
  5. // STL list需要重载 operators =, == and <.  
  6.   
  7. class AAA  
  8. {  
  9.    friend ostream &operator<<(ostream &, const AAA &);  
  10.   
  11.    public:  
  12.       int x;  
  13.       int y;  
  14.       float z;  
  15.   
  16.       AAA();  
  17.       AAA(const AAA &);  
  18.       ~AAA(){};  
  19.       AAA &operator=(const AAA &rhs);  
  20.       int operator==(const AAA &rhs) const;  
  21.       int operator<(const AAA &rhs) const;  
  22. };  
  23.   
  24. AAA::AAA()   // 构造函数  
  25. {  
  26.    x = 0;  
  27.    y = 0;  
  28.    z = 0;  
  29. }  
  30.   
  31. AAA::AAA(const AAA &in)   // 复制构造函数,传值  
  32. {                               
  33.    x = copyin.x;  
  34.    y = copyin.y;  
  35.    z = copyin.z;  
  36. }  
  37.   
  38. ostream &operator<<(ostream &output, const AAA &aaa)  
  39. {  
  40.    output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl;  
  41.    return output;  
  42. }  
  43.   
  44. AAA& AAA::operator=(const AAA &rhs)  
  45. {  
  46.    this->x = rhs.x;  
  47.    this->y = rhs.y;  
  48.    this->z = rhs.z;  
  49.    return *this;  
  50. }  
  51.   
  52. int AAA::operator==(const AAA &rhs) const  
  53. {  
  54.    ifthis->x != rhs.x) return 0;  
  55.    ifthis->y != rhs.y) return 0;  
  56.    ifthis->z != rhs.z) return 0;  
  57.    return 1;  
  58. }  
  59.   
  60. //该函数是为了让STL list支持sort  
  61. int AAA::operator<(const AAA &rhs) const  
  62. {  
  63.    ifthis->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1;  
  64.    ifthis->x == rhs.x && this->y < rhs.y) return 1;  
  65.    ifthis->x < rhs.x ) return 1;  
  66.    return 0;  
  67. }  
  68.   
  69. main()  
  70. {  
  71.    list<AAA> L;  
  72.    AAA Ablob ;  
  73.   
  74.    Ablob.x=7;  
  75.    Ablob.y=2;  
  76.    Ablob.z=4.2355;  
  77.    L.push_back(Ablob);  // 在末尾插入一个新元素  
  78.   
  79.    Ablob.x=5;  
  80.    L.push_back(Ablob);  // 传值,用默认的拷贝构造函数  
  81.                         //   
  82.    Ablob.z=3.2355;  
  83.    L.push_back(Ablob);   
  84.   
  85.    Ablob.x=3;  
  86.    Ablob.y=7;  
  87.    Ablob.z=7.2355;  
  88.    L.push_back(Ablob);   
  89.   
  90.    list<AAA>::iterator i;  
  91.   
  92.    for(i=L.begin(); i != L.end(); ++i) cout << (*i).x << " "// print member  
  93.    cout << endl;        
  94.   
  95.    for(i=L.begin(); i != L.end(); ++i) cout << *i << " "// print with overloaded operator  
  96.    cout << endl;  
  97.   
  98.    cout << "Sorted: " << endl;  
  99.    L.sort();  
  100.    for(i=L.begin(); i != L.end(); ++i) cout << *i << " "// print with overloaded operator  
  101.    cout << endl;  
  102.   
  103.    return 0;  
  104. }  
  105.   
  106.                   
#include <iostream>
#include <list>
using namespace std;

// STL list需要重载 operators =, == and <.

class AAA
{
   friend ostream &operator<<(ostream &, const AAA &);

   public:
      int x;
      int y;
      float z;

      AAA();
      AAA(const AAA &);
      ~AAA(){};
      AAA &operator=(const AAA &rhs);
      int operator==(const AAA &rhs) const;
      int operator<(const AAA &rhs) const;
};

AAA::AAA()   // 构造函数
{
   x = 0;
   y = 0;
   z = 0;
}

AAA::AAA(const AAA &in)   // 复制构造函数,传值
{                             
   x = copyin.x;
   y = copyin.y;
   z = copyin.z;
}

ostream &operator<<(ostream &output, const AAA &aaa)
{
   output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl;
   return output;
}

AAA& AAA::operator=(const AAA &rhs)
{
   this->x = rhs.x;
   this->y = rhs.y;
   this->z = rhs.z;
   return *this;
}

int AAA::operator==(const AAA &rhs) const
{
   if( this->x != rhs.x) return 0;
   if( this->y != rhs.y) return 0;
   if( this->z != rhs.z) return 0;
   return 1;
}

//该函数是为了让STL list支持sort
int AAA::operator<(const AAA &rhs) const
{
   if( this->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1;
   if( this->x == rhs.x && this->y < rhs.y) return 1;
   if( this->x < rhs.x ) return 1;
   return 0;
}

main()
{
   list<AAA> L;
   AAA Ablob ;

   Ablob.x=7;
   Ablob.y=2;
   Ablob.z=4.2355;
   L.push_back(Ablob);  // 在末尾插入一个新元素

   Ablob.x=5;
   L.push_back(Ablob);  // 传值,用默认的拷贝构造函数
                        // 
   Ablob.z=3.2355;
   L.push_back(Ablob); 

   Ablob.x=3;
   Ablob.y=7;
   Ablob.z=7.2355;
   L.push_back(Ablob); 

   list<AAA>::iterator i;

   for(i=L.begin(); i != L.end(); ++i) cout << (*i).x << " "; // print member
   cout << endl;      

   for(i=L.begin(); i != L.end(); ++i) cout << *i << " "; // print with overloaded operator
   cout << endl;

   cout << "Sorted: " << endl;
   L.sort();
   for(i=L.begin(); i != L.end(); ++i) cout << *i << " "; // print with overloaded operator
   cout << endl;

   return 0;
}

                
输出结果:
7 5 5 3 
7 2 4.2355
 5 2 4.2355
 5 2 3.2355
 3 7 7.2355
 
Sorted:
3 7 7.2355
 5 2 3.2355
 5 2 4.2355
 7 2 4.2355
STL vector 和 list 函数比较:
Functionvectorlist
constructor yes yes
destructor yes yes
empty() yes yes
size() yes yes
resize() yes yes
capacity() yes no
reserve() yes no
max_size() yes yes
erase() yes yes
clear() yes yes
operator= yes yes
operator< yes yes
operator== yes yes
operator[] yes no
at() yes no
front() yes yes
back() yes yes
push_back() yes yes
pop_back() yes yes
assign() yes yes
insert() yes yes
swap() yes yes
push_front() no yes
pop_front() no yes
merge() no yes
remove() no yes
remove_if() no yes
reverse() no yes
sort() no yes
splice() no yes
unique() no yes
posted @ 2013-09-20 14:05  CoolRandy  阅读(274)  评论(0)    收藏  举报