C++ 笔记 关于使用仿函数来修改set容器默认排序

    科技2022-08-19  95

    set容器默认升序排序,如果需要降序排序则需要使用仿函数或者 greater<T>

    CODE部分:

    #include <iostream> #include <set> #include <ctime> #include <algorithm> using namespace std; class Mycompare { public: bool operator()(int val1, int val2) { return val1 > val2; } }; void setpoo() { srand((unsigned int)time(NULL)); set<int, Mycompare>s; //赋值 for (int i = 0; i < 10; i++) { s.insert(rand() % 10 + 20); } //遍历 set<int, Mycompare>::iterator sit; sit = s.begin(); for (; sit != s.end(); sit++) { cout << *sit << " "; } cout << endl; } int main() { setpoo(); system("pause"); return 0; }

    也可以使用greater<T>进行修改排序规则

     
    Processed: 0.015, SQL: 9