c++ pair 用法詳解
阿新 • • 發佈:2019-01-22
標準庫型別--pair型別定義在utility標頭檔案中定義
1、pair的建立和初始化
pair包含兩個數值,與容器一樣,pair也是一種模板型別。但是又與之前介紹的容器不同,在建立pair物件時,必須提供兩個型別名,兩個對應的型別名的型別不必相同
pair<string,string>anon; pair<string,int>word_count; pair<string, vector<int> >line;
當然也可以在定義時為每個成員提供初始化式:
pair<string,string>author("James","Joy");
pair型別的使用相當的繁瑣,如果定義多個相同的pair型別物件,可以使用typedef簡化宣告:
typedef pair<string,string> Author; Author proust("March","Proust"); Author Joy("James","Joy");
2、pair物件的操作
對於pair類,可以直接訪問其資料成員:其成員都是公有的,分別命名為first和second,只需要使用普通的點操作符
string firstBook; if(author.first=="James" && author.second=="Joy") firstBook="Stephen Hero";
3、生成新的pair物件
除了建構函式,標準庫還定義了一個make_pair函式,由傳遞給它的兩個實參生成一個新的pair物件
pair<string, string> next_auth; string first,last; while(cin>>first>>last) { next_auth=make_pair(first,last); //... }
還可以用下列等價的更復雜的操作:
next_auth=pair<string,string>(first,last);
由於pair的資料成員是公有的,因而可如下直接地讀取輸入:
pair<string, string> next_auth; while(cin>>next_auth.first>>next_auth.last) { //... }
4、程式設計實踐
練習:編寫程式讀入一系列string和int型資料,將每一組儲存在一個pair物件中,然後將這些pair物件儲存在vector容器
#include<iostream> #include<string> #include<vector> #include<utility> using namespace std; int main() { pair<string, int>p; typedef vector< pair<string, int> > VP; VP vp; while(cin>>p.first>>p.second) { vp.push_back(make_pair(p.first,p.second)); } VP::iterator it; for(it=vp.begin(); it!=vp.end(); it++) cout<<it->first<<","<<it->second<<endl; return 0; }