遍历成对的向量并访问第一个和第二个元素

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

我正在尝试迭代向量对并访问第一个和第二个元素。

我不能使用自动,所以我需要使用迭代器。

  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;
    }
  }

我不断收到错误消息:

Has no member named first.

我尝试过:it2->first,it2.first 和 (*it2).first.

为什么它不起作用?

您正在尝试将迭代器与字符串进行比较。这不仅涉及取消引用 it2 的语法,还必须取消引用 it。正确的语法是

if (*it == it2->first)

顺便说一句,你写错了,你写的是 it2 = class1.end() 而不是 it2 != class1.end()

改变这个:

if (it == it2.first)

对此:

if (*it == it2->first)

因为 it 遍历一个字符串向量,所以你需要取消引用它来获取实际的字符串。与 it2 类似,其中不使用 *.。在一起,您使用 -> 来简化。