C ++ STL集更新是冗长乏味:我不能更改元素的位置 [英] C++ STL set update is tedious: I can't change an element in place

查看:110
本文介绍了C ++ STL集更新是冗长乏味:我不能更改元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现更新操作非常乏味,因为在 cppreference 上没有这样的API。所以我现在做的是sth这样:

  //通过迭代器找到元素
元素copy =迭代器
... //复制时更新成员值,不同
Set.erase(iterator);
Set.insert(copy);

基本上Set的返回值是一个const_iterator,你不能直接改变它的值。 p>

有更好的方法吗?或者我应该通过创建自己的(我不知道它是如何工作的。)

重写集。

谢谢!

c> c>返回 const_iterators (标准说 set< T> :: iterator const ,并且 set< T> :: const_iterator set< T> :: iterator 实际上可能是相同的类型 - 参见n3000.pdf中的23.2.4 / 6)有序容器。如果它返回了一个常规的迭代器,你将被允许改变从容器下面的项目值,可能改变顺序。



您的解决方案是修改 set 中的项目的惯用方法。


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

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

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

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

Thanks!

解决方案

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 ++ STL集更新是冗长乏味:我不能更改元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆