簡體   English   中英

用指針理解const_iterator?

[英]Understanding const_iterator with pointers?

我試圖理解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到底是什么意思?

UPDATE

在這種情況下,使用const_iterator是最佳做法嗎?

vector<Customer*> const_iterator將為您提供Customer * const而不是Customer const* 因此,您實際上無法更改迭代的值(指針),但您確定可以更改它指向的對象。 基本上它在你的情況下說的是你不能這樣做:

*it = ..something..;

您沒有修改容器的內容。 容器的內容只是指針。 但是,您可以自由修改指針指向的任何內容。

如果您不想修改指針指向的內容,則需要vector<const Customer*>

const_iterator 不是關於是否可以修改容器,而是關於是否可以修改容器中的對象。 在你的情況下,容器包含指針,你不能修改指針本身(除了你可以修改整數...)你仍然可以在集合的指針后面調用非常量的Refresh(),因為該調用確實不要改變指針本身

當容器包含例如類實例,而不是指向它們的指針,但實例本身,例如在容器中時,const_iterator和迭代器之間的區別很重要[僅]

list < pair < int , int > >

如果'it'是這個列表中的const_iterator,你就做不到

it->first = 5

但如果它是迭代器(不是const_iterator),那就行了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM