Populate a vector with all multimap values with a given key

前端 未结 6 1672
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 13:10

Given a multimap M what\'s a neat way to create a vector of all values in M with a specific key.

e.g given a multimap how c

6条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-08 13:35

    Just some addenda to the other answers here…

    std::mem_fn (from #include ) can be used as a shorthand for the transform operator:

    // previously we might've used this longhand
    [](pair element){return element.second;}
    

    And we can use vector::resize and std::distance to allocate space for the vector in one go, rather than repeatedly resizing it with back_inserter.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    typedef multimap MapType;
    
    int main()
    {
        MapType multimap;
        vector valuesForKey123;
    
        multimap.emplace(0,   "red");
        multimap.emplace(123, "hello");
        multimap.emplace(123, "world");
        multimap.emplace(0,   "herring");
    
        MapType::iterator lower{multimap.lower_bound(123)};
        MapType::iterator upper{multimap.upper_bound(123)};
        valuesForKey123.resize(distance(lower, upper));
    
        transform(
            lower,
            upper,
            valuesForKey123.begin(),
            mem_fn(&MapType::value_type::second));
    
        copy(
            valuesForKey123.begin(),
            valuesForKey123.end(),
            ostream_iterator(cout, " "));
    }
    // outputs "hello world "
    

提交回复
热议问题