Populate a vector with all multimap values with a given key

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

    You need a loop anyway. All "loop-free" methods just abstract the loop away.

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int main () {
        multimap mm;
        mm.insert(make_pair(1, 2.2));
        mm.insert(make_pair(4, 2.6));
        mm.insert(make_pair(1, 9.1));
        mm.insert(make_pair(1, 3.1));
    
        vector v;
        transform(mm.lower_bound(1), mm.upper_bound(1),
                  back_inserter(v), __gnu_cxx::select2nd >());
        // note: select2nd is an SGI extension.
    
        for (vector::const_iterator cit = v.begin(); cit != v.end(); ++ cit)
            printf("%g, ", *cit);   // verify that you've got 2.2, 9.1, 3.1
        return 0;
    }
    

提交回复
热议问题