代码之家  ›  专栏  ›  技术社区  ›  Codeforces Fan

如何在c中的STL集合中添加lambda函数或执行自定义操作++

  •  0
  • Codeforces Fan  · 技术社区  · 1 年前

    我需要一个集合以这样的方式排列值,如果int值不同,我需要字母表上较大的字符串放在前面,否则我需要较小的整数放在前面

    set<pair<int,string>,[&](auto &a,auto &b){
        if(a.first==b.first)return a.second>b.second;
        return a.first<b.first;
    }>;
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Vlad from Moscow    1 年前

    看起来你的意思是

    #include <iostream>
    #include <string>
    #include <utility>
    #include <set>
    #include <tuple>
    
    
    int main()
    {
        auto less = []( const auto &p1, const auto &p2 )
        {
            return std::tie( p1.first, p2.second ) < 
                   std::tie( p2.first, p1.second );
        };
        std::set<std::pair<int, std::string>, decltype( less )> 
        s( { { 1, "A" }, { 1, "B" }, { 2, "A" } }, less );
    
        for ( const auto &p : s )
        {
            std::cout << p.first << ' ' << p.second << '\n';
        }
    }
    

    1 B
    1 A
    2 A
    

    也可以使用不带初始值设定项列表的构造函数

        std::set<std::pair<int, std::string>, decltype( less )> 
        s( less );