Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these appropriate practices when working with std::map?

I have some questions on using std::map:

  1. Is using an enum as the key in std::map a good practice? Consider the following code:

    enum Shape{
        Circle,
        Rectangle
    };
    
    int main(int argc, char* argv[])
    {
         std::map<Shape,std::string> strMap;
         // strMap.insert(Shape::Circle,"Circle"); // This will not compile
         strMap[Shape::Circle] = "Circle";         // But this will work
         return 0;
    }
    
  2. In the above example, why is the call to insert() generating a compiler error while the overloaded [] operator works correctly? Which of these methods is recommended for inserting items into a std::map?

  3. I understand that when the find() method is used on the std::map class, it is not doing a sequential search in the container but doing some logarithmic search which will be much faster than sequential search. Is this understanding correct?

like image 230
Navaneeth K N Avatar asked Jan 28 '09 18:01

Navaneeth K N


3 Answers

  1. Having an enum as key_type is not bad by itself. (edit) But if you only use sequential enum-values, a std::vector with O(1) access is even better.
  2. insert must be used like this: mapVar.insert(make_pair(key, value)); See also cppreference.com.
  3. Yes, std::map has O(log(n)) lookup, as guaranteed by the standard, and this is faster than O(n) if n is sufficiently high.
like image 81
gimpf Avatar answered Nov 10 '22 01:11

gimpf


Insert fails because the value_type is std::pair

like image 29
Alan Avatar answered Nov 10 '22 00:11

Alan


1) Is keeping an enum as key in std::map a good practice?

Well, for efficiency, with such a small enum, you'd be better off with a vector or tr1::array of either values (if your value type supports 'empty' values) or smart pointers. ex: vector<string>

For correctness -- I believe you're fine. Map can work with any key type that is sortable -- that is, that have operator<, or for which you provide a sorting function. Enums have ordering by default

2) In strMap.insert(Shape::Circle,"Circle") why insert method is [giving] a compiler error?

Because insert doesn't take two values. it takes a pair. try:

#include <utility>
...
strMap.insert(make_pair(Circle, string("Circle")));

3) When find() method is used in the map class, [it's] doing some logarithmic search ... correct?

Yes. map::find is O(lg(map::size())) time. map stores its key-value pairs in a data structure sorted by key. insert and erase are O(lg(n)), as is find. It also provides bidirectional iterators, meaning that you can find the next or previous item in the map in O(1) constant time, but you cannot skip forward and backward more than one element at a time.

Edit: corrected that enums have ordering by default.

like image 28
2 revs Avatar answered Nov 10 '22 00:11

2 revs