[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Access map element wrong using operator []
From: |
Thomas Maeder |
Subject: |
Re: Access map element wrong using operator [] |
Date: |
Wed, 01 Feb 2006 09:01:28 +0100 |
User-agent: |
Gnus/5.1006 (Gnus v5.10.6) XEmacs/21.4 (Jumbo Shrimp, linux) |
Long Li <lilongll@gmail.com> writes:
> #include <iostream>
> using std::cout;
> using std::endl;
Side note: std::endl is declared in <ostream>, not <iostream> (not
necessarily anyway). You'd have to #include <ostream> as well.
> #include <string>
> using std::string;
> #include <vector>
> using std::vector;
> #include <map>
> using std::map;
> class A{
> public:
> map<string, vector<string> > MapInA;
> };
> void f1( const map<string, A> &aaa ){
> map<string, A>::const_iterator it = aaa.begin();
it is a const_iterator, so what it refers to is const ...
> while( it != aaa.end() ){
> if( it->second.MapInA.count( "ID" ) ){
> cout << (*it).second.MapInA[ "ID" ][ 0 ] << endl;
... including members of it, such as it->second.MapInA.
operator[], on the other hand, is non-const for maps, because an
element will be added to the map for the given index if the map
doesn't already contain such an element.
> }
> it++;
> }
> }
> void f2( const map<string, A> &aaa ){
> map<string, A>::const_iterator it = aaa.begin();
> map<string, vector<string> >::const_iterator it2;
> while( it != aaa.end() ){
> if( it->second.MapInA.count( "ID" ) ){
> it2 = it->second.MapInA.find( "ID" );
The find() member function is const, so this is accepted.
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Re: Access map element wrong using operator [],
Thomas Maeder <=