laterSon
laterSon

Reputation: 303

How to access ith member of map?

I want to access any member of map in c++. Like in if I have a
map = {(4,3), (5,6), (9,8)}
and say I want to to get second member of this map. I tried

map<int, int>::iterator it = mpp.begin();
cout << (it+1)->first << " " << (it+1)->second << endl;

I didn't get any success. Please help me out.

Upvotes: 1

Views: 906

Answers (2)

eerorika
eerorika

Reputation: 238311

Only random access iterators have overloads for operator+ and operator-. Bidirectional iterators such as std::map::iterator do not. They can however be advanced linearly by using std::next (since C++11) which will

Return the nth successor of iterator it.

or std::advance which

Increments given iterator it by n elements.


PS. Note that the complexity for finding n'th element of a std::map has linear complexity. There are other similar data structures provide the features that std::map has, but also allow for faster n'th member lookup. So, and alternative data structure might more appropriate for your use case.

For example, a binary search tree can be augmented with the size of each subtree. Such structure is named order statistic tree. For the small linear increase in memory overhead, it gives O(log n) complexity for finding n'th element.

Upvotes: 1

laterSon
laterSon

Reputation: 303

I rather applied a simple method. Say I have to get jth element from the begging.

map<int, int>::iterator it = mpp.begin();
while(j--)
          it++;
cout << it->first << " " << it -> second << endl;

Upvotes: 0

Related Questions