在C ++中获取多图的价值

时间:2011-10-07 02:02:33

标签: c++ map multimap

我想知道如何在C ++中检索多地图的值

2 个答案:

答案 0 :(得分:10)

Multimap的内部结构表示为std::pair<T_k, T_v>。它有第一,第二成员。 first是密钥,second是与密钥关联的值。

#include <iostream>
#include <map>

using namespace std;

int main(){

        multimap<int,int> a;
        a.insert(pair<int,int> (1,2));
        a.insert(pair<int,int> (1,2));
        a.insert(pair<int,int> (1,4));
        for (multimap<int,int>::iterator it= a.begin(); it != a.end(); ++it) {
                cout << it->first << "\t" << it->second << endl ;
        }

        return 0;
}

输出:

  

1 2
  1 2
  1 4

答案 1 :(得分:7)

要检索multimap的值,您需要使用其名称。

因此,如果您有一个名为myMap的多图,您可以使用以下表达式检索其值:

myMap

获得其值后,可以将其复制到另一个多图中,或者可以在其上调用成员函数将其值分解为较小的逻辑子值。


要访问与给定键(在此示例中名为myKey)对应的特定范围的映射值,您可以使用:

myMap.equal_range(myKey)

这评估为std::pair iterator(如果const_iteratorsmyMap,则为const),用于界定键值对的范围密钥等同于myKey

例如(假设myMap是从T1到T2的映射,其中T1和T2不是依赖类型):

typedef std::multimap<T1, T2>::iterator iter;
for (std::pair<iter, iter> range(myMap.equal_range(myKey));
     range.first != range.second;
     ++range.first)
{
    //In each iteration range.first will refer to a different object
    //In each case, range.first->first will be equivalent to myKey
    //and range.first->second will be a value that range.first->first maps to.
}