c++ - Does const containers have only const iterator? -


why const stl containers return const_iterators?

for example both std::vector , std::list have method begin overloaded as:

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

i thought still modify values of const vector not vector itself. according standard library there no difference between:

const std::vector<int> 

and

const std::vector<const int> 

suppose have

iterator begin() const; 

instead of

const_iterator begin() const; 

now, think happens when have

const vector<foo> v; 

you able like

*v.begin() = other_foo; 

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

the situation similar having const classes have pointer members. in cases, may modify data pointer points (but not pointer itself), logical const-ness not preserved. standard library took step forward , disallowed these kind of modifications on standard containers via const overloads return const_iterators.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -