Re: Modify STL map Object
Daniel T. <daniel_t@earthlink.net> wrote:
Just keep in mind, every time you use op[] you are doing a
logarithmic search
So do std::map::find() and std::map::insert(). So what?
Calling find once is better than calling op[] multiple times.
And calling operator[] once is better than calling find() multiple times.
So what?
Maybe your point is that it's too easy to just call operator[] every
time you need to access an element, even when you are accessing the
same element many times in succession, whereas find() is telling more
explicitly that a "find this element in the tree" operation will be
performed, thus in a way "warning" the programmer that it's not an
extremely quick operation. operator[] resembles array indexing, which
might give the wrong impression that it's a constant-time operation.
Ok, fair enough. Of course you should know what the operator[] is
doing, and if you want to make repeated operations to the same element,
you should use a reference (ie. "type& element = theMap[value];" and
then use 'element' for the multiple operations).
However, std::map::operator[] is still handier than find()+insert()
when what you want is automatic insertion if the element doesn't exist.
I don't understand. operator[] *does* add the element if it didn't
exist.
What if you don't want to add the element if it doesn't exist?
Your original point was about insert(), and how it doesn't when the
element already exists, to which I pointed out that operator[] is much
handier for that purpose.