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

女生的网名这么多〃 提交于 2019-12-24 03:54:10

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/21692681/does-the-auto-keyword-know-when-to-use-a-const-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!