I have a std::unordered_map
std::unordered_map<std::string, std::string> myMap;
I want to get a const iterator using find. In c++03 I would do
std::unordered_map<std::string, std::string>::const_iterator = myMap.find("SomeValue");
In c++11 I would want to use auto instead to cut down on the templates
auto = myMap.find("SomeValue");
Will this be a const_iterator or iterator? How does the compiler decide which to use? Is there a way I can force it to choose const?
Automatic type deduction is one of the most important and widely used features in modern C++. The new C++ standards have made it possible to use auto as a placeholder for types in various contexts and let the compiler deduce the actual type.
The auto keyword in C++ automatically detects and assigns a data type to the variable with which it is used. The compiler analyses the variable's data type by looking at its initialization. It is necessary to initialize the variable when declaring it using the auto keyword.
A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can't be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed).
The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.
It will use non-const iterators if myMap
is a non-const expression. You could therefore say
#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);
}
And then
auto it = const_(myMap).find("SomeValue");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With