C++ std::pair 与 std::make_pair
来源:互联网 发布:广州婚纱摄影排名 知乎 编辑:程序博客网 时间:2024/06/06 04:06
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);
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 }
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
2 The price of lightbulbs is $0.99
3 The price of shoes is $20
0 0
- std::pair 与 std::make_pair
- std::pair 与 std::make_pair
- C++ std::pair 与 std::make_pair
- C++ std::pair 与 std::make_pair
- C++ std::pair 与 std::make_pair
- C++ std::pair 与 std::make_pair
- C++学习 std:pair与std:make_pair
- C++ std::pair 与 std::make_pair
- c++中的std::pair与std::make_pair
- c++ std::pair 与 std::make
- std::pair
- std::pair<>
- C++ std::pair, std::tuple
- pair与make_pair
- pair 与 make_pair
- std::pair, std::copy, std::lower_bound, std::back_insert使用
- 扩展std::pair
- C++ std::pair
- IntelliJ Idea 常用快捷键
- Mac中使用mysql数据库基础(上)
- 覆盖,重写,重载,隐藏,多态的区别(一下子清晰了)
- cocos2d-x +lua
- Foreman配置bug
- C++ std::pair 与 std::make_pair
- Storm – Kafka – Cassandra for Big Data System
- OpenGL环境设置
- kettle4.1源码研究
- Android 圆形ImagView
- Android源码--startActivityUncheckedLocked
- 选项卡选中状态的实现及其多个选项时按钮的状态切换((每个选项其实都是按钮))
- for循环,unsigned short
- MySQL索引背后的数据结构及算法原理