1. 程式人生 > >演算法筆記-6.8 pair用法

演算法筆記-6.8 pair用法

#include<stdio.h>
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
	pair<string,int>p("haha",5);
	cout<<p.first<<" "<<p.second<<endl;
	p=make_pair("xixi",5);
	cout<<p.first<<" "<<p.second<<endl;
	p=pair<string,int>("hehe",5);
	cout<<p.first<<" "<<p.second<<endl;
}

/*
------------pair是將兩個元素綁在一起作為一個合成元素,又不使用結構體---------
1.pair的定義
    方法一:pair<typeName1,typeName2>name; p.first=xxx;p.second=xxx;
    方法二:pair<typeName1,typeName2>name("xxx","xxx");//直接賦值
    方法三:p=make_pair("xixi",5);//臨時搭建pair
2.pair的元素訪問
    p.first--->第一個元素   p.second--->第二個元素
3.pair元素的比較
    可採用==、!=、<、>、<=、>=
    比較規則是先比較first 如果相同 則比較second
4.pair的用途
    1.替換二元結構體
    2.作為map的鍵值輸入
        如:map<string,int>mp;
            mp.insert(make_pair("heihei",5));
            mp.insert(pair<string,int>("haha",5));
            for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
                count<<it.first<<it.second<<endl;
            }


*/