I have some questions on using std::map
:
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;
}
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
?
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?
std::vector
with O(1) access is even better.insert
must be used like this: mapVar.insert(make_pair(key, value));
See also cppreference.com.std::map
has O(log(n)) lookup, as guaranteed by the standard, and this is faster than O(n) if n is sufficiently high.Insert fails because the value_type is std::pair
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With