First question: is it possible to \"force\" a const_iterator
using auto?
For example:
map usa
This isn't a drastically different take on conversion to const
in comparision to @Jollymorphic's answer, but I think that having a utility one-liner function like this is handy:
template<class T> T const& constant(T& v){ return v; }
Which makes the conversion much more appealing to the eye:
auto it = constant(usa).find("New York");
// other solutions for direct lengths comparision
std::map<std::string, int>::const_iterator city_it = usa.find("New York");
auto city_it = const_cast<const std::map<std::string, int>&>(usa).find("New York");
Well, I'd say, bigger isn't always better. You can of course choose the name of the function according to your preferences - as_const
or just const_
are possible alternatives.
In C++11, you can do this:
decltype(usa)::const_iterator city_it = usa.find("New York");