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

Ste*_*ris 2 c++ map multimap

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

Mah*_*esh 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 2
1 2
1 4


Man*_*rse 7

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

因此,如果您调用了多图myMap,则可以使用以下表达式检索其值:

myMap
Run Code Online (Sandbox Code Playgroud)

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


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

myMap.equal_range(myKey)
Run Code Online (Sandbox Code Playgroud)

这个计算结果为std::pairiteratorS(或const_iterators如果myMapconst),其限定键-值对的与等效于密钥的范围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.
}
Run Code Online (Sandbox Code Playgroud)