1

If the keys of my map are dynamically generated, is there a way to get a key value at a specific offset, like the key value of the second key-value pair? I was trying to get a random key value of a map, so I just generated a random number and want to extract the corresponding key with this offset. I don't whether it's the way to achieve that. Or is there a normal method? Thanks!

user8822312
  • 255
  • 4
  • 14
  • Sounds like XY problem, why do you need a map if you access by offset? – Slava Apr 11 '18 at 00:57
  • I don't know whether is there any other way to get a random key value, maybe not accessing by offset? But I think I have to use map in my case. – user8822312 Apr 11 '18 at 01:02
  • A map is sorted by key, so the offsets of things can change as you add more items. It's possible this is the wrong container for you. A vector of pairs or structs might be more useful if you need easy random access. – Retired Ninja Apr 11 '18 at 01:03

1 Answers1

3

You can use std::next.

std::map<int, int> myMap;
auto itAtOffset = std::next(myMap.begin(), offset);

If you do not have C++ 11, you can use std::advance instead.

std::map<int, int> myMap;
std::map<int, int>::iterator itAtOffset = myMap.begin();
std::advance(itAtOffset, offset);

Note that the complexity is O(N), so if you want faster method, you should consider storing the data in different structure.

hgminh
  • 1,178
  • 1
  • 8
  • 26