Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a const_iterator using auto?

Tags:

c++

c++11

auto

First question: is it possible to "force" a const_iterator using auto? For example:

std::map<std::string, int> usa;
//...init usa
auto city_it = usa.find("New York");

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?

like image 617
virtualPN Avatar asked Mar 05 '13 20:03

virtualPN


3 Answers

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.

Just write it this way:

std::map<std::string, int>::const_iterator city_it = usa.find("New York");

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");
like image 80
Andy Prowl Avatar answered Nov 05 '22 05:11

Andy Prowl


Since C++17 you can use std::as_const like this:

#include <utility>

// ...

auto city_it = std::as_const(usa).find("New York");
like image 35
jhasse Avatar answered Nov 05 '22 03:11

jhasse


A clean solution is to work with a const reference to the otherwise modifiable map:

const auto &const_usa = usa;
auto city_it = const_usa.find("New York");

This will make sure you can't modify const_usa, and will use const iterators.

like image 13
rustyx Avatar answered Nov 05 '22 03:11

rustyx