我有一个 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?
最佳答案
如果 myMap
是一个非常量表达式,它将使用非常量迭代器。因此你可以说
#include <type_traits>
#include <utility>
template<typename T, typename Vc> struct apply_vc;
template<typename T, typename U> struct apply_vc<T, U&> {
typedef T &type;
};
template<typename T, typename U> struct apply_vc<T, U&&> {
typedef T &&type;
};
template<typename T>
typename apply_vc<typename std::remove_reference<T>::type const, T&&>::type
const_(T &&t) {
return std::forward<T>(t);
}
然后
auto it = const_(myMap).find("SomeValue");
关于c++ - 如何使用自动变量选择迭代器类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9453383/