我发现更新操作std::set很繁琐,因为cppreference上没有这样的API .所以我现在做的是这样的:
//find element in set by iterator
Element copy = *iterator;
... // update member value on copy, varies
Set.erase(iterator);
Set.insert(copy);
Run Code Online (Sandbox Code Playgroud)
基本上迭代器返回的Set是a const_iterator,你不能直接改变它的值.
有一个更好的方法吗?或者也许我应该std::set通过创建我自己的(我不知道它是如何工作的...)来覆盖.
我正在学习 C++ 的自学课程,学习标准库的工作原理,我想了解这段代码是如何for_each工作的,特别是关于变异对象(与本机数据类型相反)。我意识到你不应该使用for_each这种方式,但这是为了学习。
我原以为这段代码会改变集合中的所有元素,但事实并非如此。
我的问题是: 1. 为什么这段代码不会改变集合?2.如何代码被修改,以便它会修改的设置?澄清一下:有没有办法保留for_each并让它操纵集合,或者这是不可能的并且transform必须使用其他一些方法(例如)?
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
class A {
int a;
public:
A(int a) : a(a) {}
int getA() const { return a; }
void setA(int a) { this->a = a; }
bool operator<(const A & b) const { return a<b.a; }
};
struct myprinter {
void operator()(const A & a) { cout << a.getA() …Run Code Online (Sandbox Code Playgroud) 我试过这样做:
std::set< pair<int, int> > mySet;
// fill the set with something
mySet.find( make_pair(someValueX, someValueY) )->first = newX;
Run Code Online (Sandbox Code Playgroud)
但是我在编译时遇到以下错误:
error: assignment of member 'std::pair<int, int>::first' in read-only object|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===||
Run Code Online (Sandbox Code Playgroud)