Tomas Sykora
Tomas Sykora

Reputation: 471

Iterate throught std::vector inside std::map

I would appreciate your help on my trouble. I am desperate, feel like idiot, but obviously I cannot figure it out by my self.

I have a vector inside map

map<string, vector<string>>SubjectsAndTeachers

I have it filled with data such as:

[0] = {
  first = "OSY"
  second = size=1 {
    [0] = "lada"
      }
}
[1] = {
  first = "PA1"
  second = size=4 {
    [0] = " honza"
    [1] = "lada"
    [2] = "mirek  "
    [3] = "pepa"
      }
}
[2] = {
  first = "PA2"
  second = size=3 {
    [0] = " honza"
    [1] = "lada"
    [2] = "pepa"
}
        .
        .
        .
        .

What it need is simply, iterate all of them to print them into console. So far I have came up with:

for(map<string, vector<string> >::const_iterator it = SubjectsAndTeachers.begin();  it != SubjectsAndTeachers.end(); ++it)
{
    cout << it->first << ": ";
    for (vector<string>::const_iterator b = it->second.begin(); b != it->second.end() ;++it)
    {
        cout << *b;
    }
    cout << endl;
}

I am trying to get:

OSY : lada
PA1 : honza lada mirek pepa
     .
     .
     .
     .

But this doesnt seem to work.

Please could someone help?

Upvotes: 2

Views: 10772

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

To simplify the task you could use the range based for statemeent. For example

for ( const auto &p : SubjectsAndTeachers )
{
    cout << p.first << " :";
    for ( const auto &s : p.second )
    {
        cout << ' ' << s;
    }
    cout << endl;
}

As for your code then you increment iterator it in the inner loop instead of iterator b.

Upvotes: 3

hivert
hivert

Reputation: 10667

You second loop look suspicious:

for (vector<string>::const_iterator b = it->second.begin(); b != it->second.end() ;++it)
                                                                                   ^^^^

You certainly mean ++b...

Upvotes: 4

Related Questions