开发者

Getting the value of a multimap in C++

I was wondering how do I retrieve the value of a mult开发者_如何学Pythoni map in 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 a a given key (called myKey in this example), you can use:

myMap.equal_range(myKey)

This evaluates to a std::pair of iterators (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.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜