2014-12-03 145 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<>{});