From: Gerhard Wolf on
Hi,

i try to iterate trough a 'vector of map'. The
vector<map<string,string> > c;
is correctly filled with data.

cout << c[0]["RDB$RELATION_NAME"] << endl;
works fine but:

for (vector<map<string,string> >::const_iterator it =
c.begin() ; it != c.end(); ++it) {
cout << *it["RDB$RELATION_NAME"] << endl;
}

does not. What am i doing wrong here?
From: Ben Bacarisse on
Gerhard Wolf <quisquiliae(a)gmx.de> writes:

> i try to iterate trough a 'vector of map'. The
> vector<map<string,string> > c;
> is correctly filled with data.
>
> cout << c[0]["RDB$RELATION_NAME"] << endl;
> works fine but:
>
> for (vector<map<string,string> >::const_iterator it =
> c.begin() ; it != c.end(); ++it) {
> cout << *it["RDB$RELATION_NAME"] << endl;

cout << (*it)["RDB$RELATION_NAME"] << endl;

> }
>
> does not. What am i doing wrong here?

*it is the map referred to by it, but [...] binds more tightly than *.

--
Ben.
From: Stuart Golodetz on
Ben Bacarisse wrote:
> Gerhard Wolf <quisquiliae(a)gmx.de> writes:
>
>> i try to iterate trough a 'vector of map'. The
>> vector<map<string,string> > c;
>> is correctly filled with data.
>>
>> cout << c[0]["RDB$RELATION_NAME"] << endl;
>> works fine but:
>>
>> for (vector<map<string,string> >::const_iterator it =
>> c.begin() ; it != c.end(); ++it) {
>> cout << *it["RDB$RELATION_NAME"] << endl;
>
> cout << (*it)["RDB$RELATION_NAME"] << endl;
>
>> }
>>
>> does not. What am i doing wrong here?
>
> *it is the map referred to by it, but [...] binds more tightly than *.

The other problem is that he's using a const_iterator -- map doesn't
have a const operator[].

If you're sure every map contains that key, you could (but I wouldn't)
do something like:

std::cout << it->find("RDB$RELATION_NAME")->second << '\n';

The better way is to do:

map<string,string>::const_iterator jt = it->find("RDB$RELATION_NAME");
if(jt != it->end()) cout << jt->second << '\n';

Or something along those lines...

Here's a minimal compileable example, for the OP's benefit:

#include <iostream>
#include <map>
#include <string>
#include <vector>

int main()
{
typedef std::map<std::string,std::string> Map;
typedef std::vector<Map> Vec;
Vec vec(2);
vec[0]["Blah"] = "0";
vec[1]["Blah"] = "1";
for(Vec::const_iterator it=vec.begin(), iend=vec.end(); it!=iend; ++it)
{
Map::const_iterator jt = it->find("Blah");
if(jt != it->end()) std::cout << jt->second << '\n';
}
return 0;
}

Regards,
Stu