我试图迭代一对对矢量并访问第一和第二元素。
我不能使用auto,所以我需要使用迭代器。
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;
}
}
我一直在收到错误:
没有成员名字第一。
我试过了:it2->首先,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
,而不是使用*
和.
。在一起,你使用->
轻松。