c++vectordictionarycopy

Conditionally copy map keys to a vector


I have a std::map container. I want to copy all its keys with user specified first letters to a vector. How to do that in an efficient way?

std::map<std::string, std::size_t> myMap;
myMap.insert(std::make_pair("Ace", 11));
myMap.insert(std::make_pair("Ape", 12));
myMap.insert(std::make_pair("Age", 13));
myMap.insert(std::make_pair("Beat", 21));
myMap.insert(std::make_pair("Boat", 22));
myMap.insert(std::make_pair("Boss", 23));
myMap.insert(std::make_pair("Coat", 31));
myMap.insert(std::make_pair("Cost", 32));
myMap.insert(std::make_pair("Cast", 33));

For example, if I want to extract all the element(s) with their keys starting with "Bo" from myMap and populate the satisfled results to myVec, myVec will have the following elements:

Boat
Boss

Solution

  • Declarations left out for brevity:

    begin = myMap.lower_bound("Bo");
    end = std::find_if(begin, myMap.end(), first_does_not_begin_with("Bo"));
    for (i=begin; i!=end; ++i)
        myVec.push_back(i->first);
    

    You can implement the first_does_not_begin_with functor class, right? It's operator should have this signature:

    bool operator()(std::pair<const std::string, size_t> const &);