STL map詳細用法和make_pair函數

 

今天練習華爲上機測試題,遇到了map的用法,看來博客http://blog.csdn.net/sprintfwater/article/details/8765034;感受很詳細,博主的其餘內容也值得學習;後面附上今天的練習題目。ios

 

首先make_pair

Pairs 
C++標準程序庫中凡是「必須返回兩個值」的函數, 也都會利用pair對象 
class
pair能夠將兩個值視爲一個單元。容器類別map和multimap就是使用pairs來管理其健值/實值(key/va
lue)的成對元素。 
pair被定義爲struct,所以可直接存取pair中的個別值.
兩個pairs互相比較時, 第一個元素正具備較高的優先級. 
例: 
namespace std{ 
template <class T1, class T2> 
bool operator< (const pair<T1, T2>&x, const pair<T1, T2>&y){ 
return x.first<y.first || ((y.first<x.first)&&x.second<y.second); 
} 
}
make_pair():
無需寫出型別, 就能夠生成一個pair對象 
例: 
std::make_pair(42, '@'); 
而沒必要費力寫成: 
std::pair<int, char>(42, '@')
當有必要對一個接受pair參數的函數傳遞兩個值時, make_pair()尤爲顯得方便, 
void f(std::pair<int, const char*>);
void foo{ 
f(std::make_pair(42, '@')); //pass two values as pair 
}
1 pair的應用
pair是將2個數據組合成一個數據,當須要這樣的需求時就可使用pair,如stl中的map就是將key和value放在一塊兒來保存。另外一個應用是,當一個函數須要返回2個數據的時候,能夠選擇pair。 pair的實現是一個結構體,主要的兩個成員變量是first second 由於是使用struct不是class,因此能夠直接使用pair的成員變量。
2 make_pair函數
template pair make_pair(T1 a, T2 b) { return pair(a, b); }
很明顯,咱們可使用pair的構造函數也可使用make_pair來生成咱們須要的pair。 通常make_pair都使用在須要pair作參數的位置,能夠直接調用make_pair生成pair對象很方便,代碼也很清晰。 另外一個使用的方面就是pair能夠接受隱式的類型轉換,這樣能夠得到更高的靈活度。靈活度也帶來了一些問題如:
std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
是不一樣的,第一個就是float,而第2個會本身匹配成double。


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,23,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個字節的,一個父節點指針,左右孩子指針,還有一個枚舉值(標示紅黑的,至關於平衡二叉樹中的平衡因子),我想你們應該知道,這些地方很費內存了吧,不說了……

 

//題目描述
//
//數據表記錄包含表索引和數值,請對錶索引相同的記錄進行合併,即將相同索引的數值進行求和運算,輸出按照key值升序進行輸出。
//
//輸入描述 :
//先輸入鍵值對的個數
//而後輸入成對的index和value值,以空格隔開
//
//
//輸出描述 :
//輸出合併後的鍵值對(多行)

//#include<iostream>
//#include<map>
//using namespace std;
//
//int main(int, char**){
//    int count;
//    cin >> count;
//    int a, b;
//    map<int, int> maps;
//    for (int i = 0; i != count; i++){
//        cin >> a >> b;
//      //用insert函數插入數據,在數據的插入上涉及到集合的惟一性這個概念,即當map中有這個關鍵字時,
//        //insert操做是插入數據不了的,可是用數組方式就不一樣了,它能夠覆蓋之前該關鍵字對應的值,用程序說明
//        maps[a] += b;
//    }
//    typedef map<int, int>::iterator Iter;
//    for (Iter iter = maps.begin(); iter != maps.end(); iter++){
//        cout << iter->first << " " << iter->second << "\n";
//    }
////    getchar();
////    getchar();
//    return 0;
//}

#include<iostream>
#include<map>
using namespace std;
int main()

{
    int value, key;
    int n;
    while (cin>>n)
    {
        map<int, int> maps;
        for (size_t i = 0; i < n; i++)
        {
            cin >> key >> value;
            //用insert函數插入數據,在數據的插入上涉及到集合的惟一性這個概念,即當map中有這個關鍵字時,
            //insert操做是插入數據不了的,可是用數組方式就不一樣了,它能夠覆蓋之前該關鍵字對應的值,用程序說明
            pair<map<int, int>::iterator, bool > rel = maps.insert(make_pair(key,value));   
            if (!rel.second) //若是插入key存在,即沒有插入成功,則累加value
            {
                rel.first->second += value;
            }
        }
        for (auto it = maps.begin(); it !=maps.end(); it++)
        {
            cout << (*it).first << " " << (*it).second << endl;
        }
    }
    system("pause");
    return 0;
}


//#include <iostream>
//#include <map>
//#include <set>
//using namespace std;
//int main()
//{    int inSum;
//    while (cin >> inSum)
//    {
//        int key, value;
//        set<int> si;
//        map<int, int> mii;
//        while (inSum--)
//        {
//            cin >> key;
//            si.insert(key);
//            cin >> value;
//            mii[key] = mii[key] + value;
//        }
//        set<int>::iterator it;
//        for (it = si.begin(); it != si.end(); it++)
//        {
//            cout << *it << " " << mii[*it] << endl;
//        }
//    }
//    return 0;
//
//}
相關文章
相關標籤/搜索