提问者:小点点

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


我想在比较的时候改变一个集合的元素,像这样:-

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

但是它不工作,你能告诉我如何才能做到这一点吗??


共1个答案

匿名用户

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

守则中的其他问题:

  • 不要#include
  • 不使用命名空间标准
  • 比较函数应为常量。
  • compare函数应该通过常量引用获取参数; 否则,它将收到它们的副本。

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

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

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|更改|集合|中|元素|值|c++|中)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?