Re: Overhead of subscript operator for STL maps
On 2008-10-17 09:43, Stephen Horne wrote:
On Thu, 16 Oct 2008 20:32:13 +1300, Ian Collins <ian-news@hotmail.com>
wrote:
The subscript operator creates a default constructed object then copies
the passed object to it. So you will see a copy for the operator call
and one for the copy in.
Wow!
I always assumed that using [] for a key that isn't already in the
container would throw an exception. It seems like an obvious case of
most-likely-a-mistake to me.
I realise that scripting languages do it, but they get to handle the
[] differently depending on whether its on the left side of an
assignment or not. They still complain if you try to read a
non-existent key.
And even with the [] on the left of an assignment, I still think it's
a bit bad, since to me the obvious intent is to overwrite the data for
an existing key.
Personally I consider it a good idea, it can simplify a lot of code
(such as this one, written by Fred Swartz):
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> freq; // map of words and their frequencies
string word; // input buffer for words.
//--- Read words/tokens from input stream
while (cin >> word) {
freq[word]++;
}
//--- Write the count and the word.
map<string, int>::const_iterator iter;
for (iter=freq.begin(); iter != freq.end(); ++iter) {
cout << iter->second << " " << iter->first << endl;
}
return 0;
}//end main
Notice how little code is dedicated to the actual counting of the words.
--
Erik Wikstr??m