本文介绍了使用给定键使用所有多映射值填充向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 multimap M,用一个特定的键创建一个 vector 的 M 中所有值的巧妙方法是什么.

Given a multimap<A,B> M what's a neat way to create a vector<B> of all values in M with a specific key.

例如,给定一个多重映射,我如何获得映射到值 123 的所有字符串的向量?

e.g given a multimap how can I get a vector of all strings mapped to the value 123?

答案很简单,从下限->上限循环,但是有没有一种简洁的无循环方法?

An answer is easy, looping from lower->upper bound, but is there a neat loop-free method?

推荐答案

这是 STL 风格的方法:

Here's the way to do it STL style :

// The following define is needed for select2nd with DinkumWare STL under VC++
#define _HAS_TRADITIONAL_STL 1

#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <functional>
#include <map>
#include <iterator>
#include <iostream>

using namespace std;

void main()
{
    typedef multimap<string, int> MapType;
    MapType m;
    vector<int> v;

    // Test data
    for(int i = 0; i < 10; ++i)
    {
        m.insert(make_pair("123", i * 2));
        m.insert(make_pair("12", i));
    }

    MapType::iterator i = m.lower_bound("123");
    MapType::iterator j = m.upper_bound("123");

    transform(i, j, back_inserter(v), select2nd<MapType::value_type>());

    copy(v.begin(), v.end(),  ostream_iterator<int>(cout, ","));

}

这篇关于使用给定键使用所有多映射值填充向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:03