对于大多数容器,iterator
type 提供对容器中值的读写访问,const_iterator
类型提供只读访问。但是,对于 std::set<T>
,迭代器类型无法提供读写访问,因为修改集合中的值(可能)会破坏容器不变量。因此,在 std::set<T>
, 两者 iterator
和 const_iterator
提供只读访问权限。
这引出了我的问题:使用 std::set<T>::iterator
可以做的事情之间有什么区别吗?以及你可以用 std::set<T>::const_iterator
做的事情?
请注意,在 C++11 中,容器的操作方法(例如 erase
)可以采用 const_iterator
。参数。
最佳答案
不,它们之间在功能上没有太大区别。当然,曾经回到C++03,当set<T>::iterator
没有返回 const T&
.但是一旦他们改变了它,他们就被两种不同类型的迭代器所困,这两种迭代器都做同样的事情。
事实上,标准非常清楚它们具有相同的功能(到它们可以是相同类型的程度,但不是必需的)。从 23.2.4,p。 6:
iterator
of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, bothiterator
andconst_iterator
are constant iterators. It is unspecified whether or notiterator
andconst_iterator
are the same type. [ Note:iterator
andconst_iterator
have identical semantics in this case, anditerator
is convertible toconst_iterator
. Users can avoid violating the One Definition Rule by always usingconst_iterator
in their function parameter lists. —end note ]
关于c++ - std::set::iterator 和 std::set::const_iterator 之间是否存在操作差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283302/