java map 与 pair,STL 之 pair 和map

STL的头文件中描述了一个非常简单的模板类pair,用来表示一个二元组或元素对,并提供了大小比较的比较运算符模板函数。

pair模板类需要两个参数:首元素的数据类型和尾元素的数据类型。pair模板类对象有两个成员:first和second,分别表示首元素和尾元素。

在中已经定义了pair上的六个比较运算符:、<=、>=、==、!=,其规则是先比较first,first相等时再比较second,这符合大多数应用的逻辑。当然,也可以通过重载这几个运算符来重新指定自己的比较逻辑。

例子程序:// map/pair-test.cpp - Show basic use of pair. // 2004-02-29 - Fred Swartz - Rodenbach #include #include #include #include using namespace std; int main() { //-- Declare a pair variable. pair pr1; //-- Declare and initialize with constructor. pair pr2("heaven", 7); cout << pr2.first << "=" << pr2.second << endl; // Prints heaven=7 //-- Declare and initialize pair pointer. pair* prp = new pair("yards", 9); cout << prp->first << "=" << prp->second << endl; // Prints yards=9 //-- Declare map and assign value to keys. map 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::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对象,也可以调用在中定义的一个模板函数: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 #include using namespace std; /* STL pair data type containing int and float */ typedef struct pair 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; }

0 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值