標准庫 pair 介紹
問題:map里的元素由key和value組成,這個key和value的組合是什么類型呢???
答案:pair類型
pair介紹:
- 它是模板
- 有2個公有成員可供訪問。 first和second。
- make_pair函數能返回一個pair
- 可以進行 ==,!=,<=,<, >, >=運算
//由參數1和2推導出類型為<int, int>
auto ap1 = make_pair(1, 2);
pair<int, int> ap2(ap1);
小例子:
#include <iostream>
#include <vector>
using namespace std;
pair<string, int> process(vector<string> &v){
if(!v.empty()){
return pair<string, int>(v.back(), v.back().size());
}
else{
return pair<string, int>();
}
}
int main(){
pair<string, string> p1{"",""};
pair<string, size_t> cnt{"last",5};
pair<string, vector<int>> li;
cout << cnt.first << " " << cnt.second << endl;
vector<string> svec{"aa", "last"};
pair<string, size_t> cnt2 = process(svec);
cout << cnt2.first << " " << cnt2.second << endl;
if(cnt2 == cnt){
cout << "euqal" << endl;
}
if(cnt2 < cnt){
cout << "less" << endl;
}
//由參數1和2推導出類型為<int, int>
auto ap1 = make_pair(1, 2);
pair<int, int> ap2(ap1);
}
c/c++ 學習互助QQ群:877684253
本人微信:xiaoshitou5854