STL中的模板类pair
来源:互联网 发布:免费速读训练软件 编辑:程序博客网 时间:2024/04/28 12:47
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;
- }
0 0
- STL中的模板类pair
- STL中的模板类pair 和map
- STL中的模板类pair 和map
- STL中的模板类pair ,make_pair和map
- STL中的模板类pair 和map http://blog.csdn.net/calvin_zcx/article/details/6072286
- [STL基础]pair组对单位模板类
- STL中的Pair方法详解
- STL中的Pair方法详解
- 标准模板库(STL)使用---pair
- c++ stl pair类用法
- STL Pair
- pair(STL)
- [STL] pair
- STL::pair
- STL-pair
- stl pair
- STL pair
- STL中的模板类map的介绍
- [C++]内存分配的概念
- JSTL中的核心标签库(EL)
- Edius简易教程
- 最优化方法的Matlab实现
- htmlUnit的使用
- STL中的模板类pair
- iOS软件开发常见通过Cocoapods安装的第三方框架
- HDU 3567 Eight II
- 迁移学习(transfer learning)、多任务学习(multi-task learning)、深度学习(deep learning)概念摘抄
- HDU5476 Explore Track of Point【计算几何】
- 编译原理:第七节
- 面试小记-2-找出二维数组里连续的'A'
- LeetCode:Maximum Depth of Binary Tree
- UVa 10215 - The Largest/Smallest Box ...