how to get an iterator from map. for example: m [1] = 1; m [2] = 2 .... m [100000] = 100000 and how to get the iterator m [100000] in c ++. m is a map, 100000 is a key

  • Get what input data? By sequence number in sequence? By key? - AnT

2 answers 2

The question is not clearly formulated.

  • If we are talking about an iterator for the last element of a sequence, then this is

    auto it = std::prev(m.end()); 
  • If we are talking about an iterator by sequence number in the sequence, for example

     auto it = std::next(m.begin(), 100000); 
  • If we are talking about an iterator using the map key, then

     auto it = m.find(100000); 
  • thank. have helped. this is an iterator using the map key. - luka mosiashvili
 #include <iostream> #include <map> #include <string> int main() { std::map<int, std::string> map = {{1,"one"}, {2,"two"},{3,"three"}}; auto nx = std::next(map.begin(), 2); std::cout<<nx->first<<" "<<nx->second << std::endl; } 
  • Thanks, but this code does not work on gnu c ++ 11, but I need code for gnu c ++ 11 - luka mosiashvili
  • @luka mosiashvili: No need to invent. This code works great on gnu c ++ 11. - AnT
  • one
    @lukamosiashvili, compile with -std = c ++ 11 - xperious flag