C++ std::pair<>
2016-01-20 10:41
791 查看
std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair<int,float> 或者 std::pair<double,double>等。pair实质上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。初始化一个pair可以使用构造函数,也可以使用std::make_pair函数,make_pair函数的定义如下:
template pair make_pair(t1 a, t2 b) { return pair(a, b); }
一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象。另一个使用的方面就是pair可以接受隐式的类型转换,这样可以获得更高的灵活度。但是这样会出现如下问题:例如有如下两个定义:
std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
其中第一个的second变量是float类型,而make_pair函数会将second变量都转换成double类型。这个问题在编程是需要引起注意。下面是一段pair与make_pair的例子程序:
1 #include <iostream>
2 #include <utility>
3 #include <string>
4 using namespace std;
5
6 int main () {
7 pair <string,double> product1 ("tomatoes",3.25);
8 pair <string,double> product2;
9 pair <string,double> product3;
10
11 product2.first = "lightbulbs"; // type of first is string
12 product2.second = 0.99; // type of second is double
13
14 product3 = make_pair ("shoes",20.0);
15
16 cout << "the price of " << product1.first << " is $" << product1.second << "\n";
17 cout << "the price of " << product2.first << " is $" << product2.second << "\n";
18 cout << "the price of " << product3.first << " is $" << product3.second << "\n";
19 return 0;
20 }
其运行结果如下:
1 the price of tomatoes is $3.25
2 the price of lightbulbs is $0.99
3 the price of shoes is $20
template pair make_pair(t1 a, t2 b) { return pair(a, b); }
一般make_pair都使用在需要pair做参数的位置,可以直接调用make_pair生成pair对象。另一个使用的方面就是pair可以接受隐式的类型转换,这样可以获得更高的灵活度。但是这样会出现如下问题:例如有如下两个定义:
std::pair<int, float>(1, 1.1);
std::make_pair(1, 1.1);
其中第一个的second变量是float类型,而make_pair函数会将second变量都转换成double类型。这个问题在编程是需要引起注意。下面是一段pair与make_pair的例子程序:
1 #include <iostream>
2 #include <utility>
3 #include <string>
4 using namespace std;
5
6 int main () {
7 pair <string,double> product1 ("tomatoes",3.25);
8 pair <string,double> product2;
9 pair <string,double> product3;
10
11 product2.first = "lightbulbs"; // type of first is string
12 product2.second = 0.99; // type of second is double
13
14 product3 = make_pair ("shoes",20.0);
15
16 cout << "the price of " << product1.first << " is $" << product1.second << "\n";
17 cout << "the price of " << product2.first << " is $" << product2.second << "\n";
18 cout << "the price of " << product3.first << " is $" << product3.second << "\n";
19 return 0;
20 }
其运行结果如下:
1 the price of tomatoes is $3.25
2 the price of lightbulbs is $0.99
3 the price of shoes is $20
相关文章推荐
- 重学C++ (六) 标准IO库
- c语言中的static
- c++程序猿经典面试题
- c++中的243、251、250错误原因
- C++设计模式——单例模式
- C++之路进阶——可持续化线段树(Couriers)
- C++之路进阶——(可持续化线段树)
- 关于 C++ 框架、库和资源的一些汇总列表
- C++模板(二)
- C语言冒泡排序法心得
- VC++ 中使用内存映射文件处理大文件
- c++模板(一)
- Qt & C++变量类型装换
- 论“使用C++非内置全局变量的风险”
- 解决VTune错误.../lib64/libstdc++.so.6: version `GLIBCXX_3.4.14' not found (required by ...)
- thiscall仅仅应用于“C++”成员函数(this指针存放于CX寄存器,参数从右到左压)
- C++编译时函数名修饰约定规则(很具体),MFC提供的宏,extern "C"的作用
- C++中如何用cout实现输出的填充,宽度,对齐及其精度控制
- C++ 自定义日期类实现日期的加减算法
- C++ 实现mystring类型