Search code examples
c++vectoriteratorstd-pair

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?


Solution

  • 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().