0

Are there any methods of procuring an iterator, when working with a Standard Library map container, which don't require searching throughout the container?

I have a managing class for a map, and I wish to return the iterator associated to items added to the map. I don't want to rely upon find() if at all possible. If I can avoid searches I figure all the better.

std::map<char, bool>::iterator ClassA::Add(char item)
{
  mymap[item] = false;
  return mymap.get_iterator_lastitem();
}

Perhaps

return mymap.end() - 1;
Josh C
  • 1,035
  • 2
  • 14
  • 27
  • http://stackoverflow.com/questions/326062/in-stl-maps-is-it-better-to-use-mapinsert-than – Retired Ninja Aug 01 '14 at 05:20
  • Most containers have an `insert` method that returns an iterator, `map` is [no exception](http://en.cppreference.com/w/cpp/container/map/insert) (although it returns the iterator as a pair). – user657267 Aug 01 '14 at 05:21
  • 3
    See [`std::map::insert`](http://en.cppreference.com/w/cpp/container/map/insert). Also, as `std::map` is sorted, adding a new item using the index operation (like `mymap[key] = data`) the new item may not be the "last" item in the map. – Some programmer dude Aug 01 '14 at 05:21
  • First person to post this as an answer gets the points. Thanks regardless. – Josh C Aug 01 '14 at 05:23

1 Answers1

1

If you're not using C++11, then

std::map<char, bool>::iterator ClassA::Add(char item)
{
   std::pair<std::map<char, bool>::iterator, bool> result = mymap.insert(std::make_pair(item, false));
   if(!result.second) {
       // Item already exists, modify that existing item
       result.first->second = false;
   }

   return result.first;
}

If you are using C++11 then it is better to use emplace + auto.

std::map<char, bool>::iterator ClassA::Add(char item)
{
   auto result = mymap.emplace(item, false);
   if(!result.second) {
      // Item already exists, modify that existing item
      result.first->second = false;
   }

   return result.first;
}

Live example

Both insert and emplace return a pair of an iterator and a boolean, of which the iterator points to the inserted or existing element and the boolean indicates whether an insertion (true) took place or if not (false) of which the returned iterator points to the already-existing element with the key.

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94