Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select iterator type using auto variable?

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?

like image 596
Jim Jeffries Avatar asked Feb 26 '12 13:02

Jim Jeffries


People also ask

Is using Auto good practice C++?

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.

What is Auto type C++?

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.

What is the difference between iterator and Const_iterator?

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).

Why do we use auto in C++?

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.


1 Answers

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");
like image 94
Johannes Schaub - litb Avatar answered Oct 13 '22 08:10

Johannes Schaub - litb