我如何得到一个const_iterator使用汽车? [英] How do I get a const_iterator using auto?

查看:97
本文介绍了我如何得到一个const_iterator使用汽车?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个问题:是否可以使用auto强制一个 const_iterator
例如:

First question: is it possible to "force" a const_iterator using auto? For example:

map<int> usa;
//...init usa
auto city_it = usa.find("New York");

我只想查询,而不是改变 city_it ,所以我想让 city_it map< int> :: const_iterator 。但是通过使用auto, city_it map :: find()的返回类型相同, code> map< int> :: iterator 。任何建议?

I just want to query, instead of changing anything pointed by city_it, so I'd like to have city_it to be map<int>::const_iterator. But by using auto, city_it is the same to the return type of map::find(), which is map<int>::iterator. Any suggestion?

推荐答案

很抱歉,我认为最好的建议是 $ c> auto ,因为您想要执行(隐式有效的)类型转换 auto 是用于推导确切类型,这不是您想要的。

Sorry, but I just think the best suggestion is not using auto at all, since you want to perform a (implicitly valid) type conversion. auto is meant for deducing the exact type, which is not what you want here.

只需这样写:

std::map<std::string, int>::const_iterator city_it = usa.find("New York");

正如MooingDuck正确指出的,使用类型别名可以提高代码的可读性和可维护性: / p>

As correctly pointed out by MooingDuck, using type aliases can improve the readability and maintainability of your code:

typedef std::map<std::string, int> my_map;
my_map::const_iterator city_it = usa.find("New York");

这篇关于我如何得到一个const_iterator使用汽车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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