How do I get a const_iterator using auto?

前端 未结 8 1778
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 08:18

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

map usa         


        
相关标签:
8条回答
  • 2020-12-13 09:08

    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.

    0 讨论(0)
  • 2020-12-13 09:11

    In C++11, you can do this:

    decltype(usa)::const_iterator city_it = usa.find("New York");
    
    0 讨论(0)
提交回复
热议问题