Populate a vector with all multimap values with a given key

前端 未结 6 1670
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  -上瘾入骨i
    2021-02-08 13:40

    You could initialise the vector by giving it two iterators, like this:

    std::multimap bar;
    
    ...
    
    std::vector > foo(bar.lower_bound("123"), bar.upper_bound("123"));
    

    but that would give you a vector of pairs (ie, with both the key and value).

    Another option would be to use std::copy with something like a back_inserter, which is another way to hide the loop, but with the same downside as above.

    std::copy(bar.lower_bound("123"), bar.upper_bound("123"), std::back_inserter(foo));
    

    This would append the elements (if any) to the vector foo.

    For extracting the values only, I can't think of any way but to loop over the results as I'm not aware of a standard way to get only the value out of a range.

提交回复
热议问题