2014-12-03 105 views
1

我想知道如何对一对结构中的值进行排序。任何指针都非常感谢。对一对值进行排序

最小的工作示例粘贴在下面。

#include <iostream> 

using namespace std; 

int main() 
{ 

pair <int, int> myPair; 
myPair = make_pair(5, 3); 
cout << myPair.first << " " << myPair.second << endl; 

return 0; 
} 
+2

等['的std :: minmax'](http://www.cplusplus.com/reference/algorithm/minmax/)代替'的std :: make_pair'? – 2014-12-03 10:14:10

+0

@PiotrS。 minmax适用于整数。关于字符串呢? – Andrej 2014-12-03 10:32:56

+2

@Andrej'minmax'默认使用*小于*运算符,这也适用于'std :: string'(希望你不是指'const char *')。 'minmax'也可以用任意二进制比较器来定制,比如'std :: minmax(5,3,std :: greater <> {})' – 2014-12-03 10:36:01

回答

2

std::pair<U,V>本身不提供任何订购功能。如果你不想写上自己的任何额外的代码(如条件std::swap),那么你可以得到最接近的是使用std::minmax而不是std::make_pair

#include <algorithm> 

std::pair<int, int> myPair = std::minmax(5, 3); 

默认情况下,std::minmax将使用less-比运算符(<)确定元素的顺序。它可以任意地被定制:

std::pair<int, int> a = std::minmax(5, 3, [](auto x, auto y){ return x*10 < y+20; }); 

std::pair<std::string, std::string> b = std::minmax("foo"s, "bar"s, std::greater<>{});