ponikoli
ponikoli

Reputation: 25

Iterate over a vector of pairs and access first and second element

I am trying to iterate over a vector of pairs and access first and second elements.

I cannot use auto, so I need to use the iterator.

  for (list<string>::const_iterator it = dest.begin(); it != dest.end(); ++it)
  {
    for (vector< pair < string, string > >::iterator it2 = class1.begin(); it2 = class1.end(); ++it2)
    {
      if (it == it2.first)
        cout << it2.second;
    }
  }

I keep getting errors:

Has no member named first.

I have tried: it2->first, it2.first and (*it2).first.

Why is it not working?

Upvotes: 1

Views: 2616

Answers (2)

gsamaras
gsamaras

Reputation: 73366

Change this:

if (it == it2.first)

to this:

if (*it == it2->first)

since it iterates over a vector of string, so you need to dereference it to take the actual string. Similarly for it2, where instead of using * and .. together, you use -> for easiness.

Upvotes: 1

patatahooligan
patatahooligan

Reputation: 3321

You are trying to compare an iterator to a string. This isn't only about the syntax to dereference it2, you also have to dereference it. The proper syntax is

if (*it == it2->first)

By the way you've made a typo, you've written it2 = class1.end() instead of it2 != class1.end().

Upvotes: 1

Related Questions