本文介绍了C ++ std :: set更新很乏味:我无法就地更改元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 std :: set 上的更新操作很乏味,因为。因此,我目前正在执行的操作是这样的:

I find the update operation on std::set tedious since there's no such an API on cppreference. So what I currently do is something like this:

//find element in set by iterator
Element copy = *iterator;
... // update member value on copy, varies
Set.erase(iterator);
Set.insert(copy);

基本上, Set 的迭代器返回是 const_iterator ,您不能直接更改其值。

Basically the iterator return by Set is a const_iterator and you can't change its value directly.

是否有更好的方法?或者也许我应该通过创建自己的方法来覆盖 std :: set (我不知道它是如何工作的。)

Is there a better way to do this? Or maybe I should override std::set by creating my own (which I don't know exactly how it works..)

推荐答案

set 返回 const_iterators (标准说 set< T> :: iterator const ,而 set< T> :: const_iterator set< T> :: iterator 实际上可能是同一类型-参见n3000.pdf中的23.2.4 / 6),因为它是订购的容器。如果它返回常规的 iterator ,则允许您从容器下方更改项目的值,从而可能更改顺序。

set returns const_iterators (the standard says set<T>::iterator is const, and that set<T>::const_iterator and set<T>::iterator may in fact be the same type - see 23.2.4/6 in n3000.pdf) because it is an ordered container. If it returned a regular iterator, you'd be allowed to change the items value out from under the container, potentially altering the ordering.

您的解决方案是更改集合中项目的惯用方式。

Your solution is the idiomatic way to alter items in a set.

这篇关于C ++ std :: set更新很乏味:我无法就地更改元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:07