Populate a vector with all multimap values with a given key

前端 未结 6 1673
伪装坚强ぢ
伪装坚强ぢ 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:49

    template 
    vector& getValues(multimap& multi, Key& key)
    {
        typedef multimap::iterator imm;
        static vector vect;
        static struct 
        {
            void operator()(const pair& p) const
            {
                vect.push_back(p.second);
            }
        } Push;
    
        vect.clear();
        pair range = multi.equal_range(key);
        for_each(range.first, range.second, Push);
        return vect;
    }
    

    This is a bit contrived because of your 'no loop' requirement.

    I prefer:

    template 
    vector getValues(multimap& map, Key& key)
    {
        vector result;
        typedef multimap::iterator imm;
        pair range = map.equal_range(key);
        for (imm i = range.first; i != range.second; ++i)
            result.push_back(i->second);
        return result;
    }
    

提交回复
热议问题