如何使用 auto 获取 const_iterator? [英] How do I get a const_iterator using auto?
问题描述
第一个问题:是否可以使用 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
.但是通过使用auto,city_it
与map::find()
的返回类型相同,即map
>.有什么建议吗?
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?
推荐答案
抱歉,我只是认为最好的建议是不要使用 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 正确指出的那样,使用类型别名可以提高代码的可读性和可维护性:
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");
这篇关于如何使用 auto 获取 const_iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!