如何在比较时更改集合元素的值(在 c++ 中)?

How can i change values of elements of a set while comparing (in c++)?

本文关键字:c++ 集合 比较 元素      更新时间:2023-10-16

我想在比较时更改集合的元素,如下所示:-

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

但是它不起作用,你能告诉我我该怎么做吗?

你不能。std::set中的元素是不可变的。您必须从集合中删除该项目,对其进行更改,然后将其添加回来。

代码中的其他问题:

  • 不要#include<bits/stdc++.h>
  • 不要using namespace std;
  • 您的比较函数应该是常量。
  • 你的比较函数应该通过 const 引用来获取它的参数;否则它会收到它们的副本。

修复比较函数签名中的最后两项:

bool operator()(pair<int,int> const & a, pair<int,int> const & b) const