使用列表/迭代器(C++)进行愚蠢的编译错误

Jus*_*tin 0 c++ iterator compiler-errors

以下不编译,我不能为我的生活看到原因!

#include <list>
using namespace std;

list<char> myList;
list<int>::iterator it;

it = myList.begin();
Run Code Online (Sandbox Code Playgroud)

错误:

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::list<_Ty>::_Iterator<_Secure_validation>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)

ale*_*xkr 5

这是因为list<char> and list<int>两个不同的类.所以他们的迭代器也是不同的类型.
如果你看一下std :: list类代码,你会看到类似的东西:

typedef _Iterator<_SECURE_VALIDATION_DEFAULT> iterator;
Run Code Online (Sandbox Code Playgroud)

要么

typedef _Iterator<bla_bla_bla> iterator;
Run Code Online (Sandbox Code Playgroud)

这意味着新类型由每个不同的类列表定义.换句话说,每个列表定义自己的迭代器类型.

将您的代码更改为:

list<char>::iterator it;
Run Code Online (Sandbox Code Playgroud)

  • 这通常意味着你需要休息一下;) (2认同)