Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the 'auto' keyword know when to use a const iterator?

If you're looping through a container as such:

typedef std::vector<std::unique_ptr<BaseClass>> Container;
Container container;

for(Container::const_iterator element = container.begin(); element != container.end(); element++)
{
    //Read through values
}

And instead of using the typedef you decide to use auto:

std::vector<std::unique_ptr<BaseClass>> container;

for(auto element = container.begin(); element != container.end(); element++)
{
    //Read through values
}

Assuming you don't alter the values, does the auto keyword use a const iterator over a non const one?

This question is curiosity more than anything, the only reason I can see this being an applicable question in a real life scenario would be if you needed to communicate that you weren't to alter values to another person working on the code.

like image 579
Nick Savage Avatar asked Dec 05 '25 16:12

Nick Savage


1 Answers

1) Use cbegin and cend to be explicit about using const iterator.

2) begin() and end() return const_iterator when method is declared as const

like image 90
segfault Avatar answered Dec 07 '25 14:12

segfault



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!