Home > other >  how to add lambda function or perform custom operation in STL set in c
how to add lambda function or perform custom operation in STL set in c

Time:07-25

I need a set arranges the value in such a way that if the int values are different i need the lexographically greater string to come front else i want the smaller integer to come front

set<pair<int,string>,[&](auto &a,auto &b){
    if(a.first==b.first)return a.second>b.second;
    return a.first<b.first;
}>;

CodePudding user response:

It seems you mean the following

#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';
    }
}

The program output is

1 B
1 A
2 A

You could use also the constructor without the initializer list

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