有时需要将两个不同的变量或者不同的变量类型“绑定”,那么pair和make_pair就可以实现上述功能。
先引入一个使用样例,后面在详细介绍函数内容:
// make_pair example
#include <utility> // std::pair
#include <iostream> // std::cout
int main () {
std::pair <int,int> foo;
std::pair <int,int> bar;
foo = std::make_pair (10,20);
bar = std::make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char>
std::cout << "foo: " << foo.first << ", " << foo.second << '\n';
std::cout << "bar: " << bar.first << ", " << bar.second << '\n';
return 0;
}
Output:
foo: 10, 20 bar: 10, 65 |
备注:
pair相当于定义一个结构体,两个成员变量是first和second,这两个变量可以直接使用。
可以使用make_pair()初始化pair。
==================介绍========================
一般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类型。
1.pair
class template
<utility>
std::pair
template <class T1, class T2> struct pair;
Member variables
member variable | definition |
---|---|
first | The first value in the pair |
second | The second value in the pair |
2.make_pair()
function template
<utility>
std::make_pair
Construct pair object
Constructs a
pair object with its first element set to
x and its second element set to
y.
The template types can be implicitly deduced from the arguments passed to make_pair.
pair objects can be constructed from other pair objects containing different types, if the respective types are implicitly convertible.
The function returns:
Where the types V1 and V2 are the decay equivalents of T1 and T2, respectively (except for reference_wrapper types, for which the corresponding reference type is used instead).
If T1 and/or T2 are rvalue references, the objects are moved and x and/or y are left in an undefined but valid state.
|
|
Where the types V1 and V2 are the decay equivalents of T1 and T2, respectively (except for reference_wrapper types, for which the corresponding reference type is used instead).
If T1 and/or T2 are rvalue references, the objects are moved and x and/or y are left in an undefined but valid state.
一个使用双关键字排序的样例
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool strict_weak_ordering(const pair<int,string> a, const pair<int,string> b)
{
return a.first > b.first;
}
//通过运算符重载,利用sort函数实现降序排列
int main()
{
vector<pair<int, string> > vec;
//为了避免与>>运算符混淆,所以这里中间要有个空格
vec.push_back(make_pair<int, string>(5, "bingo"));
vec.push_back(make_pair<int, string>(4, "bing"));
vec.push_back(make_pair<int, string>(6, "acbingo"));
vec.push_back(make_pair<int, string>(6, "ACBingo"));
vec[3].first++;
sort(vec.begin(), vec.end(), strict_weak_ordering);
//使用迭代器
vector<pair<int, string> >::iterator it = vec.begin(), end = vec.end();
for (;it!=end;++it) cout<<it->first<<endl;
//模拟正常数组
for (int i=0;i<vec.size();i++) cout<<vec[i].second<<endl;
return 0;
}
参考
1.https://www.cnblogs.com/acbingo/p/4556427.html
2.http://www.cplusplus.com/reference/utility/