const容器是否只有const迭代器? [英] Does const containers have only const iterator?

查看:202
本文介绍了const容器是否只有const迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么const STL容器仅返回const_iterator s?

Why do const STL containers only return const_iterators?

例如std::vectorstd::list都具有方法 begin 重载 为:

For example both std::vector and std::list have the method begin overloaded as:

iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;

我认为我仍然可以修改const向量的值,但不能修改向量本身.根据标准库,两者之间没有区别:

I thought I could still modify values of a const vector but not the vector itself. According to the standard library there is no difference between:

const std::vector<int>

const std::vector<const int>

推荐答案

假设您有

iterator begin() const;

代替

const_iterator begin() const;

现在,想想当你有空之后会发生什么

Now, think what happens when you have

const vector<Foo> v;

您将可以执行类似的操作

You will be able to do something like

*v.begin() = other_foo;

如果您要保留逻辑常数,那么哪个当然不合法.因此,解决方案是每当在const实例上调用迭代器时,使返回类型为const_iterator.

which of course shouldn't be legal if you want to preserve logical const-ness. The solution is therefore to make the return type const_iterator whenever you invoke iterators on const instances.

这种情况类似于具有指针成员的const类.在这些情况下,您可以修改指针指向的数据(但不能修改指针本身),因此不会保留逻辑常数.标准库向前迈了一步,并禁止通过返回const_iteratorconst重载对标准容器进行此类修改.

The situation is similar to having const classes that have pointer members. In those cases, you may modify the data the pointer points to (but not the pointer itself), so logical const-ness is not preserved. The standard library took a step forward and disallowed these kind of modifications on standard containers via const overloads that return const_iterators.

这篇关于const容器是否只有const迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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