2011-11-04 43 views
5

我想了解const_iterator的含義。我有以下示例代碼:瞭解帶指針的const_iterator?

void CustomerService::RefreshCustomers() 
{ 
    for(std::vector<Customer*>::const_iterator it = customers_.begin(); 
     it != customers_.end() ; it ++) 
    { 
     (*it)->Refresh(); 
    } 
} 

Refresh()處於Customer類中的方法,它沒有被定義爲常量。起初我以爲我認爲const_iterator應該禁止修改容器的元素。但是,此代碼無需投訴即可編譯。這是因爲有一個額外的間接進行的水平? const_iterator究竟做了什麼?

UPDATE

而在這樣的情況下,是否使用常量性最佳做法?

+0

「修改」意味着'* it = some_other_thing',這不是你正在做的事情。 –

回答

10

A const_iterator over vector<Customer*>會給你一個Customer * const而不是Customer const*。所以你實際上不能改變被迭代的值(一個指針),但你肯定可以改變它指向的對象。基本上它說你的情況是,你不能這樣做:

*it = ..something..; 
4

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

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

2

const_iterator是不是關於是否可以修改容器,但是關於是否可以修改容器中的對象。在你的情況下,容器包含指針,你不能修改指針本身(除了你可以修改整數...)你仍然可以在集合中的指針後面調用非const的Refresh(),因爲那個調用會不改變指針本身

const_iterator和iterator之間的區別是很重要的[只有]當你的容器包含例如類實例,而不是指向他們,但實例本身,例如在容器

list < pair < int , int > > 

如果「它」是一個常量性進入這個名單,你不能這樣做

it->first = 5 

但如果它是迭代器(不是const_iterator),可以工作。

+0

它也關於你是否可以修改容器 - 可以用'iterator'而不是'const_iterator'來調用'erase'和'insert'等函數。 –

+0

@MikeSeymour不像你說的那樣。你仍然可以使用'erase'和'insert'與'const_iterator'。實際上,C++ 11明確地改變了這些,以採用'const_iterator'而不是'iterartor':http://www.cplusplus.com/reference/list/list/insert/ http://www.cplusplus.com /參考/列表/列表/擦除/ – jbx