c++ - std::set::iterator 和 std::set::const_iterator 之间是否存在操作差异?

标签 c++ c++11 iterator set containers

对于大多数容器,iterator type 提供对容器中值的读写访问,const_iterator类型提供只读访问。但是,对于 std::set<T> ,迭代器类型无法提供读写访问,因为修改集合中的值(可能)会破坏容器不变量。因此,在 std::set<T> , 两者 iteratorconst_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, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type. [ Note: iterator and const_iterator have identical semantics in this case, and iterator is convertible to const_iterator. Users can avoid violating the One Definition Rule by always using const_iterator in their function parameter lists. —end note ]

关于c++ - std::set::iterator 和 std::set::const_iterator 之间是否存在操作差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12283302/

相关文章:

c++ - 自 lambda 进入 C++ 以来, `Callback` 接口(interface)是否已过时?

c++ - 为什么C++中没有placement delete表达式?

c# - 这是遍历 .NET LinkedList 并删除元素的好方法吗?

c++ - boost::range::join 一个自定义调用中的多个范围

c++ - unique_ptr 不在编译器资源管理器中生成删除指令?

C++ 多维 vector 如何在内部增长?

c++ - 覆盖另一个类中的虚方法以访问其在 C++ 中的成员

c++ - 检测容器是否具有迭代器类型

c++ - std::tuple 内存对齐

c++ - 迭代器库的正面和背面提案