C++ std::set comparator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
#include "stdafx.h" #include <iostream> #include <string> #include <set> #include <iso646.h> using namespace std;
typedef string Item;
struct decreasing_order_comparator { bool operator() (const pair<uint64_t, Item>& lhs, const pair<uint64_t, Item>& rhs) const { printf("%lld %s %lld %s\n", lhs.first, lhs.second.data(), rhs.first, rhs.second.data()); return (lhs.first > rhs.first) or (not(lhs.first > rhs.first) and lhs.second < rhs.second); } }; set<pair<uint64_t, Item>, decreasing_order_comparator> items_ordered_by_frequency;
int main() {
items_ordered_by_frequency.insert({ 5, "B" }); items_ordered_by_frequency.insert({ 3, "A" });
items_ordered_by_frequency.insert({ 2, "H" }); items_ordered_by_frequency.insert({ 1, "T" }); set<pair<uint64_t, Item>, decreasing_order_comparator>::iterator it = items_ordered_by_frequency.begin(); cout << it->first << ' ' << it->second << endl; return 0; }
|
注意C/C++可以直接使用and、or、not运算符,添加iso64.h头文件即可。
使用时,正常插入没问题,查找时遇到invalid comparator问题。
原因是comparator不符合规定。
comparator需要时strict weak ordering,需要注意的是,comparator(x,x)必须返回false。
invalid comparator问题
参考:
[1].https://stackoverflow.com/questions/9648100/using-own-comparator-operator-for-map-giving-error-in-case-if-key-not-found
[2].https://stackoverflow.com/questions/32263560/errorinvalid-comparator-when-sorting-using-custom-comparison-function
最后更新时间:
本文链接:
https://hankin2015.github.io/2017/12/08/20171208SetBug/版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!