我发现更新操作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通过创建我自己的(我不知道它是如何工作的...)来覆盖.
我有一个std::set<Foo>,我想更新其中现有元素的一些值.请注意,我正在更新的值不会更改集合中的顺序:
#include <iostream>
#include <set>
#include <utility>
struct Foo {
Foo(int i, int j) : id(i), val(j) {}
int id;
int val;
bool operator<(const Foo& other) const {
return id < other.id;
}
};
typedef std::set<Foo> Set;
void update(Set& s, Foo f) {
std::pair<Set::iterator, bool> p = s.insert(f);
bool alreadyThere = p.second;
if (alreadyThere)
p.first->val += f.val; // error: assignment of data-member
// ‘Foo::val’ in read-only structure
}
int main(int argc, char** argv){
Set s;
update(s, Foo(1, 10)); …Run Code Online (Sandbox Code Playgroud) for_each接受InputIterators:
//from c++ standard
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
Run Code Online (Sandbox Code Playgroud)
是否可以更改Function f中的对象,如下所示:
struct AddOne
{
void operator()(int & x){x = x + 1;}
};
std::vector<int> vec(10);
std::for_each(vec.begin(),vec.end(),AddOne());
Run Code Online (Sandbox Code Playgroud)
此代码适用于VC++ 2008以及GCC,但它是否也是可移植(合法)代码?
(InputIterators仅保证可用作rvalue,在这种情况下,它们在AddOne的operator()中用作左值)