Checking values in std::map

Posted by Samson on Fri 12 Jan 2007 03:40 AM — 2 posts, 16,969 views.

USA #0

CMDF( do_maptest )
{
   map<int,int> numbers;
   map<int,int>::iterator inum;

   numbers[0] = 1;
   numbers[1] = 2;
   numbers[2] = 3;
   numbers[3] = 4;
   numbers[4] = 5;

   int count = 0;
   for( inum = numbers.begin(); inum != numbers.end(); ++inum )
   {
      ++count;
      ch->printf( "Number %d:%d\r\n", inum->first, inum->second );
   }
   ch->printf( "Count #1: %d\r\n", count );

   for( int x = 0; x < 900; ++x )
   {
      if( numbers[x] == 3 )
         ch->print( "Number is 3!!\r\n" );
   }

   count = 0;
   for( inum = numbers.begin(); inum != numbers.end(); ++inum )
   {
      ++count;
      ch->printf( "Number %d:%d\r\n", inum->first, inum->second );
   }
   ch->printf( "Count #2: %d\r\n", count );
}


Darien told me that checking a std::map for a certain value, like so: if( numbers[x] == 0 ) would cause the map to throw a default value into the map at key[x]. I didn't believe him because it sounded silly, but the above function when added as a test command to my codebase returned a Count #2 value of 900, instead of the expected 5.

Is this normal expected behavior for a std::map or is this a compiler bug that needs to be reported to GNU?
Amended on Fri 12 Jan 2007 03:41 AM by Samson
USA #1
Yes, this is quite normal. The reason is that you need to create something so that you can make creating assignments.

Consider e.g.
for (int i = 0; i < 100; i++) {
  m[i] = true;
}


If it didn't create some value to return a reference for, that code would not work. Of course, this has the unfortunate consequence of the behavior you are observing.

The real way to test for presence is:
if (m.find(123) == m.end()) {
  // not present
}
else {
  // present
}


If you also want the element, you do:

map<int,bool>::iterator it;
it = m.find(123);
if (it != m.end()) {
  cout << it->first << ":" << it->second << endl;
}


(The exact syntax might not be that; it might be it->left and it->right, or something similar. But that's the basic idea.)