c++ custom compare function for std::sort()
我想为std::sort()创建自定义比较函数,以便对一些键值对std::pair进行排序。
这是我的职能
| 1 2 3 4 5 6 7 |  template <typename K, typename V> int comparePairs(const void* left, const void* right){ if((((pair<K,V>*)left)->first) <= (((pair<K,V>*)right)->first)) return 1; else return -1; } | 
然后,在一些类中,我有成对类成员的向量:
| 1 | vector<pair<K,V>> items; | 
号
以及使用std::sort()按键对向量排序的方法。
| 1 | std::sort(items.begin(), items.end(), comparePairs<K,V>); | 
我有编译错误,它说
"cannot convert parameter number from 'std::pair<_Ty1,_Ty2>' to 'const
void*'"
号
.什么是错误?
std::pair已经具有所需的比较运算符,这些运算符使用每对元素的两个元素执行词典比较。要使用它,只需为类型
还要记住,
| 1 2 | std::vector<pair<K,V>> items;  std::sort(items.begin(), items.end()); | 
如果您真的需要提供自己的比较函数,那么您需要
| 1 2 3 4 5 | template <typename K, typename V> bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs) { return lhs.first < rhs.first; } | 
请参阅:http://en.cppreference.com/w/cpp/algorithm/sort。
它说:
| 1 2 | template< class RandomIt, class Compare > void sort( RandomIt first, RandomIt last, Compare comp ); | 
- 返回的比较函数?如果第一个参数小于第二个参数,则为true。比较函数的签名应等于:bool cmp(const Type1 &a, const Type2 &b); 。
另外,这里有一个例子,说明如何使用自定义的C++ 14多态lambda使用EDCOX1 2Ω:
| 1 2 3 4 | std::sort(std::begin(container), std::end(container), [] (const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; }); | 
你的比较函数甚至没有错。
它的参数应该是存储在范围内的类型,即
它应该返回
您需要建模小于运算符,而不是
请参阅StrictWeakordering,它描述了函数必须满足的属性。