1. 程式人生 > >C++中vector和map使用詳解

C++中vector和map使用詳解

    Map是c++的一個標準容器,她提供了很好一對一的關係,在一些程式中建立一個map可以起到事半功倍的效果,總結了一些map基本簡單實用的操作!
1. map最基本的建構函式;
   map<string , int >mapstring;         map<int ,string >mapint;
   map<sring, char>mapstring;         map< char ,string>mapchar;
   map<char ,int>mapchar;            map<int ,char >mapint;

2. map新增資料;

   map<int ,string> maplive;  
   1.maplive.insert(pair<int,string>(102,"aclive"));
   2.maplive.insert(map<int,string>::value_type(321,"hai"));
   3, maplive[112]="April";//map中最簡單的插入新增!慎用,如果不存在,會把新元素插入
3,map中元素的查詢:

   find()函式返回一個迭代器指向鍵值為key的元素,如果沒找到就返回指向map尾部的迭代器。        

   map<int ,string >::iterator l_it;; 
   l_it=maplive.find(112);
   if(l_it==maplive.end())
                cout<<"we do not find 112"<<endl;
   else cout<<"wo find 112"<<endl;
4,map中元素的刪除:
   如果刪除112;
   map<int ,string >::iterator l_it;;
   l_it=maplive.find(112);
   if(l_it==maplive.end())
        cout<<"we do not find 112"<<endl;
   else  maplive.erase(l_it);

  //delete 112;
5,map中 swap的用法:
  Map中的swap不是一個容器中的元素交換,而是兩個容器交換;
  For example:
  #include <map>
  #include <iostream>

  using namespace std;

  int main( )
  {
      map <int, int> m1, m2, m3;
      map <int, int>::iterator m1_Iter;

      m1.insert ( pair <int, int>  ( 1, 10 ) );
      m1.insert ( pair <int, int>  ( 2, 20 ) );
      m1.insert ( pair <int, int>  ( 3, 30 ) );
      m2.insert ( pair <int, int>  ( 10, 100 ) );
      m2.insert ( pair <int, int>  ( 20, 200 ) );
      m3.insert ( pair <int, int>  ( 30, 300 ) );

   cout << "The original map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter->second;
      cout   << "." << endl;

   // This is the member function version of swap
   //m2 is said to be the argument map; m1 the target map
   m1.swap( m2 );

   cout << "After swapping with m2, map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
      cout  << "." << endl;
   cout << "After swapping with m2, map m2 is:";
   for ( m1_Iter = m2.begin( ); m1_Iter != m2.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
      cout  << "." << endl;
   // This is the specialized template version of swap
   swap( m1, m3 );

   cout << "After swapping with m3, map m1 is:";
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout << " " << m1_Iter -> second;
      cout   << "." << endl;
}

6.map的sort問題:
  Map中的元素是自動按key升序排序,所以不能對map用sort函式:
  For example:
  #include <map>
  #include <iostream>

  using namespace std;

 int main( )
 {
   map <int, int> m1;
   map <int, int>::iterator m1_Iter;

   m1.insert ( pair <int, int>  ( 1, 20 ) );
   m1.insert ( pair <int, int>  ( 4, 40 ) );
   m1.insert ( pair <int, int>  ( 3, 60 ) );
   m1.insert ( pair <int, int>  ( 2, 50 ) );
   m1.insert ( pair <int, int>  ( 6, 40 ) );
   m1.insert ( pair <int, int>  ( 7, 30 ) );

   cout << "The original map m1 is:"<<endl;
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout <<  m1_Iter->first<<" "<<m1_Iter->second<<endl;
  
}
  The original map m1 is:
  1 20
  2 50
  3 60
  4 40
  6 40
  7 30
  請按任意鍵繼續. . .

7,   map的基本操作函式:
      C++ Maps是一種關聯式容器,包含“關鍵字/值”對
      begin()          返回指向map頭部的迭代器
      clear()         刪除所有元素
      count()          返回指定元素出現的次數
      empty()          如果map為空則返回true
      end()            返回指向map末尾的迭代器
      equal_range()    返回特殊條目的迭代器對
      erase()          刪除一個元素
      find()           查詢一個元素
      get_allocator()  返回map的配置器
      insert()         插入元素
      key_comp()       返回比較元素key的函式
      lower_bound()    返回鍵值>=給定元素的第一個位置
      max_size()       返回可以容納的最大元素個數
      rbegin()         返回一個指向map尾部的逆向迭代器
      rend()           返回一個指向map頭部的逆向迭代器
      size()           返回map中元素的個數
      swap()            交換兩個map
      upper_bound()     返回鍵值>給定元素的第一個位置
      value_comp()      返回比較元素value的函式

 8、iterator是否為空的判斷

對於容器而言,是判斷是否為end();對於sring而言,是判斷是否是string::npos,但是如果是針對string的話,就不是"iterator",而是一般的整型值而已

9、iterator的初始化----用end()

list<char*>  list;

list<char*>::iterator it=slist.end();

---------------------------------------------------------------

map詳解:

Map是STL的一個關聯容器,它提供一對一(其中第一個可以稱為關鍵字,每個關鍵字只能在map中出現一次,第二個可能稱為該關鍵字的值)的資料處理能力,由於這個特性,它完成有可能在我們處理一對一資料的時候,在程式設計上提供快速通道。這裡說下map內部資料的組織,map內部自建一顆紅黑樹(一種非嚴格意義上的平衡二叉樹),這顆樹具有對資料自動排序的功能,所以在map內部所有的資料都是有序的,後邊我們會見識到有序的好處。

下面舉例說明什麼是一對一的資料對映。比如一個班級中,每個學生的學號跟他的姓名就存在著一一對映的關係,這個模型用map可能輕易描述,很明顯學號用int描述,姓名用字串描述(本篇文章中不用char *來描述字串,而是採用STL中string來描述),下面給出map描述程式碼:

Map<int, string> mapStudent;

1.       map的建構函式

map共提供了6個建構函式,這塊涉及到記憶體分配器這些東西,略過不表,在下面我們將接觸到一些map的構造方法,這裡要說下的就是,我們通常用如下方法構造一個map:

Map<int, string> mapStudent;

2.       資料的插入

在構造map容器後,我們就可以往裡面插入資料了。這裡講三種插入資料的方法:

第一種:用insert函式插入pair資料,下面舉例說明(以下程式碼雖然是隨手寫的,應該可以在VC和GCC下編譯通過,大家可以執行下看什麼效果,在VC下請加入這條語句,遮蔽4786警告  #pragma warning (disable:4786) )

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

第二種:用insert函式插入value_type資料,下面舉例說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(map<int, string>::value_type (1, “student_one”));

       mapStudent.insert(map<int, string>::value_type (2, “student_two”));

       mapStudent.insert(map<int, string>::value_type (3, “student_three”));

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

第三種:用陣列方式插入資料,下面舉例說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  “student_one”;

       mapStudent[2] =  “student_two”;

       mapStudent[3] =  “student_three”;

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

以上三種用法,雖然都可以實現資料的插入,但是它們是有區別的,當然了第一種和第二種在效果上是完成一樣的,用insert函式插入資料,在資料的插入上涉及到集合的唯一性這個概念,即當map中有這個關鍵字時,insert操作是插入資料不了的,但是用陣列方式就不同了,它可以覆蓋以前該關鍵字對應的值,用程式說明

mapStudent.insert(map<int, string>::value_type (1, “student_one”));

mapStudent.insert(map<int, string>::value_type (1, “student_two”));

上面這兩條語句執行後,map中1這個關鍵字對應的值是“student_one”,第二條語句並沒有生效,那麼這就涉及到我們怎麼知道insert語句是否插入成功的問題了,可以用pair來獲得是否插入成功,程式如下

Pair<map<int, string>::iterator, bool> Insert_Pair;

Insert_Pair = mapStudent.insert(map<int, string>::value_type (1, “student_one”));

我們通過pair的第二個變數來知道是否插入成功,它的第一個變數返回的是一個map的迭代器,如果插入成功的話Insert_Pair.second應該是true的,否則為false。

下面給出完成程式碼,演示插入成功與否問題

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

Pair<map<int, string>::iterator, bool> Insert_Pair;

       Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_one”));

       If(Insert_Pair.second == true)

       {

              Cout<<”Insert Successfully”<<endl;

       }

       Else

       {

              Cout<<”Insert Failure”<<endl;

       }

       Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_two”));

       If(Insert_Pair.second == true)

       {

              Cout<<”Insert Successfully”<<endl;

       }

       Else

       {

              Cout<<”Insert Failure”<<endl;

       }

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

大家可以用如下程式,看下用陣列插入在資料覆蓋上的效果

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  “student_one”;

       mapStudent[1] =  “student_two”;

       mapStudent[2] =  “student_three”;

       map<int, string>::iterator  iter;

       for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

3.       map的大小

在往map裡面插入了資料,我們怎麼知道當前已經插入了多少資料呢,可以用size函式,用法如下:

Int nSize = mapStudent.size();

4.       資料的遍歷

這裡也提供三種方法,對map進行遍歷

第一種:應用前向迭代器,上面舉例程式中到處都是了,略過不表

第二種:應用反相迭代器,下面舉例說明,要體會效果,請自個動手執行程式

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

       map<int, string>::reverse_iterator  iter;

       for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)

{

       Cout<<iter->first<<”   ”<<iter->second<<end;

}

}

第三種:用陣列方式,程式說明如下

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

       int nSize = mapStudent.size()

//此處有誤,應該是 for(int nIndex = 1; nIndex <= nSize; nIndex++)


//by rainfish

       for(int nIndex = 0; nIndex < nSize; nIndex++)

{

       Cout<<mapStudent[nIndex]<<end;

}

}

5.       資料的查詢(包括判定這個關鍵字是否在map中出現)

在這裡我們將體會,map在資料插入時保證有序的好處。

要判定一個數據(關鍵字)是否在map中出現的方法比較多,這裡標題雖然是資料的查詢,在這裡將穿插著大量的map基本用法。

這裡給出三種資料查詢方法

第一種:用count函式來判定關鍵字是否出現,其缺點是無法定位資料出現位置,由於map的特性,一對一的對映關係,就決定了count函式的返回值只有兩個,要麼是0,要麼是1,出現的情況,當然是返回1了

第二種:用find函式來定位資料出現位置,它返回的一個迭代器,當資料出現時,它返回資料所在位置的迭代器,如果map中沒有要查詢的資料,它返回的迭代器等於end函式返回的迭代器,程式說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

if(iter != mapStudent.end())

{

       Cout<<”Find, the value is ”<<iter->second<<endl;

}

Else

{

       Cout<<”Do not Find”<<endl;

}

}

第三種:這個方法用來判定資料是否出現,是顯得笨了點,但是,我打算在這裡講解

Lower_bound函式用法,這個函式用來返回要查詢關鍵字的下界(是一個迭代器)

Upper_bound函式用法,這個函式用來返回要查詢關鍵字的上界(是一個迭代器)

例如:map中已經插入了1,2,3,4的話,如果lower_bound(2)的話,返回的2,而upper-bound(2)的話,返回的就是3

Equal_range函式返回一個pair,pair裡面第一個變數是Lower_bound返回的迭代器,pair裡面第二個迭代器是Upper_bound返回的迭代器,如果這兩個迭代器相等的話,則說明map中不出現這個關鍵字,程式說明

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent[1] =  “student_one”;

       mapStudent[3] =  “student_three”;

       mapStudent[5] =  “student_five”;

       map<int, string>::iterator  iter;

iter = mapStudent.lower_bound(2);

{

       //返回的是下界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.lower_bound(3);

{

       //返回的是下界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.upper_bound(2);

{

       //返回的是上界3的迭代器

       Cout<<iter->second<<endl;

}

iter = mapStudent.upper_bound(3);

{

       //返回的是上界5的迭代器

       Cout<<iter->second<<endl;

}

Pair<map<int, string>::iterator, map<int, string>::iterator> mapPair;

mapPair = mapStudent.equal_range(2);

if(mapPair.first == mapPair.second)
       {

       cout<<”Do not Find”<<endl;

}

Else

{

Cout<<”Find”<<endl;
}

mapPair = mapStudent.equal_range(3);

if(mapPair.first == mapPair.second)
       {

       cout<<”Do not Find”<<endl;

}

Else

{

Cout<<”Find”<<endl;
}

}

6.       資料的清空與判空

清空map中的資料可以用clear()函式,判定map中是否有資料可以用empty()函式,它返回true則說明是空map

7.       資料的刪除

這裡要用到erase函式,它有三個過載了的函式,下面在例子中詳細說明它們的用法

#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

       Map<int, string> mapStudent;

       mapStudent.insert(pair<int, string>(1, “student_one”));

       mapStudent.insert(pair<int, string>(2, “student_two”));

       mapStudent.insert(pair<int, string>(3, “student_three”));

//如果你要演示輸出效果,請選擇以下的一種,你看到的效果會比較好

       //如果要刪除1,用迭代器刪除

       map<int, string>::iterator iter;

       iter = mapStudent.find(1);

       mapStudent.erase(iter);

       //如果要刪除1,用關鍵字刪除

       Int n = mapStudent.erase(1);//如果刪除了會返回1,否則返回0

       //用迭代器,成片的刪除

       //一下程式碼把整個map清空

       mapStudent.earse(mapStudent.begin(), mapStudent.end());

       //成片刪除要注意的是,也是STL的特性,刪除區間是一個前閉後開的集合

       //自個加上遍歷程式碼,列印輸出吧

}

8.       其他一些函式用法

這裡有swap,key_comp,value_comp,get_allocator等函式,感覺到這些函式在程式設計用的不是很多,略過不表,有興趣的話可以自個研究

9.       排序

這裡要講的是一點比較高深的用法了,排序問題,STL中預設是採用小於號來排序的,以上程式碼在排序上是不存在任何問題的,因為上面的關鍵字是int型,它本身支援小於號運算,在一些特殊情況,比如關鍵字是一個結構體,涉及到排序就會出現問題,因為它沒有小於號操作,insert等函式在編譯的時候過不去,下面給出兩個方法解決這個問題

第一種:小於號過載,程式舉例

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

}StudentInfo, *PStudentInfo;  //學生資訊

Int main()

{

    int nSize;

       //用學生資訊對映分數

       map<StudentInfo, int>mapStudent;

    map<StudentInfo, int>::iterator iter;

       StudentInfo studentInfo;

       studentInfo.nID = 1;

       studentInfo.strName = “student_one”;

       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

       studentInfo.nID = 2;

       studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

for (iter=mapStudent.begin(); iter!=mapStudent.end(); iter++)

    cout<<iter->first.nID<<endl<<iter->first.strName<<endl<<iter->second<<endl;

}

以上程式是無法編譯通過的,只要過載小於號,就OK了,如下:

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

       Bool operator < (tagStudentInfo const& _A) const

       {

              //這個函式指定排序策略,按nID排序,如果nID相等的話,按strName排序

              If(nID < _A.nID)  return true;

              If(nID == _A.nID) return strName.compare(_A.strName) < 0;

              Return false;

       }

}StudentInfo, *PStudentInfo;  //學生資訊

第二種:仿函式的應用,這個時候結構體中沒有直接的小於號過載,程式說明

#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

       Int      nID;

       String   strName;

}StudentInfo, *PStudentInfo;  //學生資訊

Classs sort

{

       Public:

       Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const

       {

              If(_A.nID < _B.nID) return true;

              If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;

              Return false;

       }

};

Int main()

{

       //用學生資訊對映分數

       Map<StudentInfo, int, sort>mapStudent;

       StudentInfo studentInfo;

       studentInfo.nID = 1;

       studentInfo.strName = “student_one”;

       mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

       studentInfo.nID = 2;

       studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

}

10.   另外

由於STL是一個統一的整體,map的很多用法都和STL中其它的東西結合在一起,比如在排序上,這裡預設用的是小於號,即less<>,如果要從大到小排序呢,這裡涉及到的東西很多,在此無法一一加以說明。

還要說明的是,map中由於它內部有序,由紅黑樹保證,因此很多函式執行的時間複雜度都是log2N的,如果用map函式可以實現的功能,而STL  Algorithm也可以完成該功能,建議用map自帶函式,效率高一些。

下面說下,map在空間上的特性,否則,估計你用起來會有時候表現的比較鬱悶,由於map的每個資料對應紅黑樹上的一個節點,這個節點在不儲存你的資料時,是佔用16個位元組的,一個父節點指標,左右孩子指標,還有一個列舉值(標示紅黑的,相當於平衡二叉樹中的平衡因子),我想大家應該知道,這些地方很費記憶體了吧,不說了……