我试图理解 const_iterator 的含义。我有以下示例代码:
void CustomerService::RefreshCustomers()
{
for(std::vector<Customer*>::const_iterator it = customers_.begin();
it != customers_.end() ; it ++)
{
(*it)->Refresh();
}
}
Refresh()
是 Customer
类中的一个方法,它没有定义为 const。起初我以为 const_iterator 应该禁止修改容器的元素。但是,此代码可以毫无怨言地编译。这是因为正在进行额外级别的间接访问吗? const_iterator 究竟是做什么/意味着什么?
更新
在这种情况下,使用 const_iterator 是最佳实践吗?
最佳答案
A const_iterator
在 vector<Customer*>
会给你一个Customer * const
不是Customer const*
.所以你实际上不能改变被迭代的值(一个指针),但你肯定可以改变它指向的对象。基本上它在你的情况下说的是你不能这样做:
*it = ..something..;
关于c++ - 用指针理解 const_iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017036/