'auto'关键字知道什么时候使用const迭代器? [英] Does the 'auto' keyword know when to use a const iterator?

查看:396
本文介绍了'auto'关键字知道什么时候使用const迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您像这样循环使用容器:

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
}

而不是使用typedef,你决定使用auto:

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
}

假设你不改变这些值,auto关键字使用一个const迭代器?

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)使用 cbegin cend 明确使用const迭代器。

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

2) begin() end() return const_iterator c $ c> const

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

这篇关于'auto'关键字知道什么时候使用const迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆