mardi 20 mars 2018

Why is std::map index off by one?

I am trying to get the index of the key in the map. I use distance for this. Why is the result always one off? I was expecting "ale" index to be 2 but the answer is 1.

#include <map>
#include <iostream>

int main(){

  std::map<std::string, int> my_map;

  my_map.insert(std::make_pair("apple", 0));
  my_map.insert(std::make_pair("a", 0));
  my_map.insert(std::make_pair("ale", 0));
  my_map.insert(std::make_pair("aple", 0));
  my_map.insert(std::make_pair("aplle", 0));

  std::cout << "map size = " << my_map.size() << std::endl;
  int index  = distance(my_map.begin(), my_map.find("ale"));
  std::cout << "index = " << index << std::endl;

  index  = distance(my_map.begin(), my_map.find("a"));
  std::cout << "index = " << index << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire