如何在比较时更改集合元素的值(在 c++ 中)?
How can i change values of elements of a set while comparing (in 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;
}
但是它不起作用,你能告诉我我该怎么做吗?
你不能。std::set
中的元素是不可变的。您必须从集合中删除该项目,对其进行更改,然后将其添加回来。
代码中的其他问题:
- 不要
#include<bits/stdc++.h>
- 不要
using namespace std;
- 您的比较函数应该是常量。
- 你的比较函数应该通过 const 引用来获取它的参数;否则它会收到它们的副本。
修复比较函数签名中的最后两项:
bool operator()(pair<int,int> const & a, pair<int,int> const & b) const
相关文章:
- 处理多个异常集合的C++方法
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 如何将ampl中的集合表示为c++中的向量
- 检查值是否在集合p1和p2中,但不在p3中
- 带过滤器的现代迭代c++集合
- 如何将结构插入到集合中并打印集合的成员
- 集合上的输出迭代器:assign和increment迭代器
- 如何将函数集合传递给客户端类,以便将它们当作客户端类本身的成员使用
- 实现一个在集合上迭代的模板函数
- 尝试使用集合函数时出现分段错误
- 互斥指针的集合
- c++找不到具有相同哈希的无序集合元素
- python集合的C++等价物是什么.计数器
- 如何在C++中递归地按相反顺序打印集合
- Python 集合.计数器,如何避免重复查找
- 如何写向量的无序向量集,即unordered_set<向量<向量<int>>集合?
- 从具有自定义排序的向量创建集合
- 显示字符串的集合和子集
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 有没有办法在 c++ 中按更大的 int 和更小的对对 int 和对的集合进行排序?