Item 8. Using set and map

I l @ ve RuBoard

Item 8. Using set and map

Difficulty: 5

In Item 7, we considered vector and deque . This time, the focus is on more news about the associative containers set, multiset, map , and multimap . [14]

[14] Note that set and multiset aren't really "associative" in the usual sense of relating a lookup key with another value, the way a dictionary does. That's the job of map and multimap . But all four of these containers appear in the C++ standard under the heading "Associative Contain-ers," so I'll follow suit to be consistent.

    1. What's wrong with the following code? How would you correct it?

       map<int,string>::iterator i = m.find( 13 ); if( i != m.end() ) {   const_cast<int&>( i->first ) = 9999999; } 
    2. To what extent are the problems fixed by writing the following instead?

       map<int,string>::iterator i = m.find( 13 ); if( i != m.end() ) {   string s = i->second;   m.erase( i );   m.insert( make_pair( 9999999, s ) ); } 
  1. Can you modify a set 's contents through a set::iterator ? Why or why not?

I l @ ve RuBoard


More Exceptional C++
More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions
ISBN: 020170434X
EAN: 2147483647
Year: 2001
Pages: 118
Authors: Herb Sutter

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net