简体   繁体   中英

Getting the value of a multimap in C++

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

Multimap has internal structure represented as std::pair<T_k, T_v> . It has first, second members. first is the key and second is the value associated with the key.

#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;
}

Output :

1 2
1 2
1 4

To retrieve the value of a multimap you need to use its name.

So if you have a multimap called myMap , you can retrieve its value with the expression:

myMap

Once you have its value, you can copy it into another multimap, or you can call member functions on it to decompose its value into smaller logical subvalues.


To access a particular range of mapped values that correspond to aa given key (called myKey in this example), you can use:

myMap.equal_range(myKey)

This evaluates to a std::pair of iterator s (or const_iterators if myMap is const ), which delimit the range of key-value pairs with keys that are equivalent to myKey .

For example (assume that myMap is a map from T1 to T2, where T1 and T2 are not dependent types):

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM