PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] how to add lambda function or perform custom operation in STL set in c++

 November 04, 2022     c++, declaration, lambda, set, stl     No comments   

Issue

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

Solution

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 );


Answered By - Vlad from Moscow
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing