我是C++新手,刚刚学习了迭代器。我有这样的代码:取消引用字符迭代器
//lines is a vector<string>
for (auto it = lines.begin(); it != lines.end(); ++it) {
//I want to access each characters in each element (string) of the vector
for (auto it2 = *it->begin(); it2 != *it->end(); ++it2) {
cout << *it2 << endl; //error: invalid type argument of unary '*' (have 'char')
}
cout << *it << endl; //ok
}
我测试的字符串asigning给一个变量:
string word = *it;
for (auto it2 = word.begin(); it2 != word.end(); ++it2) {
cout << *it2 << endl; //ok
}
我的问题是,为什么第二代码工作,而先不?在我看来,* it2是一个字符串,我可以使用迭代器访问它里面的字符,但事实证明,我必须将它赋值给一个变量才能工作。我不明白编译器错误。有什么不同?
'它 - >开始()'是'string'的迭代器。 '* it-> begin()'提供给你一个'char'的引用。 –