STL的<utility>头文件中描述了一个非常简单的模板类pair,用来表示一个二元组或元素对,并提供了大小比较的比较运算符模板函数。
pair模板类需要两个参数:首元素的数据类型和尾元素的数据类型。pair模板类对象有两个成员:first和second,分别表示首元素和尾元素。
在<utility>中已经定义了pair上的六个比较运算符:<、>、<=、>=、==、!=,其规则是先比较first,first相等时再比较second,这符合大多数应用的逻辑。当然,也可以通过重载这几个运算符来重新指定自己的比较逻辑。
- 例子程序:
// map/pair-test.cpp - Show basic use of pair.
// 2004-02-29 - Fred Swartz - Rodenbach
#include <utility>
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
//-- Declare a pair variable.
pair<string, int> pr1;
//-- Declare and initialize with constructor.
pair<string, int> pr2("heaven", 7);
cout << pr2.first << "=" << pr2.second << endl;
// Prints heaven=7
//-- Declare and initialize pair pointer.
pair<string, int>* prp = new pair<string, int>("yards", 9);
cout << prp->first << "=" << prp->second << endl;
// Prints yards=9
//-- Declare map and assign value to keys.
map<string, string> engGerDict;
engGerDict["shoe"] = "Schuh";
engGerDict["head"] = "Kopf";
//-- Iterate over map. Iterator value is a key-value pair.
// Iteration in map is in sorted order.
map<string, string>::const_iterator it;
for (it=engGerDict.begin(); it != engGerDict.end(); ++it) {
cout << it->first << "=" << it->second << endl;
}
// Prints head=kopf
// shoe=Schuh
system("PAUSE");
return 0;
}
除了直接定义一个pair对象外,如果需要即时生成一个pair对象,也可以调用在<utility>中定义的一个模板函数:make_pair。make_pair需要两个参数,分别为元素对的首元素和尾元素。
- 例子程序:
-
// mkpair.cpp
// compile with: /EHsc
// Illustrates how to use the make_pair function.
//
// Functions: make_pair - creates an object pair containing two data
// elements of any type.
========make_pair
#include <utility>
#include <iostream>
using namespace std;
/* STL pair data type containing int and float
*/
typedef struct pair<int,float> PAIR_IF;
int main(void)
{
PAIR_IF pair1=make_pair(18,3.14f);
cout << pair1.first << " " << pair1.second << endl;
pair1.first=10;
pair1.second=1.0f;
cout << pair1.first << " " << pair1.second << endl;
}