Populate a vector with all multimap values with a given key

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

    Let's go lambda

    given: multimap M

    requested: vector (of all values in M with a specific key 'a'.)

    method:

    std::pair aRange = M.equal_range('a')
    std::vector aVector;
    std::transform(aRange.first, aRange.second,std::back_inserter(aVector), [](std::pair element){return element.second;});         
    

    System environment:

    1. compiler: gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 (with -std=c++11)
    2. os: ubuntu 16.04

    Code example:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        typedef std::multimap MapType;
        MapType m;
        std::vector v;
    
        /// Test data
        for(int i = 0; i < 10; ++i)
        {
            m.insert(std::make_pair("123", i * 2));
            m.insert(std::make_pair("12", i));
        }
    
        std::pair aRange = m.equal_range("123");
    
        std::transform(aRange.first, aRange.second, std::back_inserter(v), [](std::pair element){return element.second;});
    
        for(auto & elem: v)
        {
            std::cout << elem << std::endl;
        }
        return 0;
    }
    

提交回复
热议问题