【发布时间】:2012-03-16 05:44:21
【问题描述】:
我有一个 std::unordered_map
std::unordered_map<std::string, std::string> myMap;
我想使用 find 获得一个 const 迭代器。在 c++03 中我会这样做
std::unordered_map<std::string, std::string>::const_iterator = myMap.find("SomeValue");
在 c++11 中,我想使用 auto 来减少模板
auto = myMap.find("SomeValue");
这是一个 const_iterator 还是迭代器?编译器如何决定使用哪个?有没有办法强制它选择 const?
【问题讨论】:
-
也许编译器正在做函数范围的类型推断......但是为什么迭代器的常量对你很重要?
-
除非我对重载的理解是错误的(或者en.cppreference.com/w/cpp/container/unordered_map/find 是错误的),
nonConstMap.find总是返回一个iterator。返回类型和您对结果的处理方式(例如,将其传递给const_iterator构造函数)不会影响选择哪个重载。也就是说,如果您调用constMap.find,它只会返回const_iterator。