-1

I want to change the elements of a set while comparing, like this :-

#include<bits/stdc++.h>
using namespace std;

struct cmp
{
    bool operator()( pair<int,int> a, pair<int,int> b)
    {
        if(a.first<=b.first)
        {
            b.first++;
        }

        return a.first<b.first;
    }
};

signed main()
{
    int n;
    cin>>n;

    set< pair<int,int> ,cmp> s;
    int position;

    for(int i=0;i<n;i++)
    {
        cin>>position;
        s.insert({position,i});
    }

    return 0;
}

However it is not working , can you tell me how can i do this??

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Aryan Agarwal
  • 23
  • 2
  • 5
  • 1
    'Change the set while comparing' The whole idea is misguided (which is why it's hard to do). Think why you need to do this and devise an approach that makes more sense. If you need any help with that please ask. – john Jun 13 '20 at 13:05
  • "it is not working" is not sufficient. What is going wrong? Yes, the obvious problem is `set`'s immutability, but please post proper [MCVE] (hint: It's not just code, it's what you feed it, what it produces, and what you expected). Also note, in this case, you accepted arguments by value, so it couldn't work even if `set` allowed it; you're modifying local copies. – ShadowRanger Jun 13 '20 at 13:06

1 Answers1

1

You cannot. Elements in a std::set are immutable. You would have to remove the item from the set, change it, and add it back.

Other issues in the code:

Fixing the last two items in the signature of the compare function:

bool operator()(pair<int,int> const & a, pair<int,int> const & b) const
cdhowie
  • 158,093
  • 24
  • 286
  • 300