Silly compile error using lists / iterators (C++)
-
06-07-2019 - |
Question
The following does not compile, and I cannot for the life of me see why!
#include <list>
using namespace std;
list<char> myList;
list<int>::iterator it;
it = myList.begin();
The error:
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)
Solution
This happens because list<char> and list<int>
are two different classes.
So their iterators are different types too.
If you look at std::list class code you will see something like:
typedef _Iterator<_SECURE_VALIDATION_DEFAULT> iterator;
or
typedef _Iterator<bla_bla_bla> iterator;
That means new type is defined by each distinct class list. In other words each list defines its own iterator type.
Change your code to this:
list<char>::iterator it;
OTHER TIPS
Because the type of the iterator is different:
list<char> myList; // char
list<int>::iterator it; // int
Beware that the type of the list or any other container is not only the template type parameter, but all other template parameters as well. For example:
list<char, MyAllocator> mylist;
list<char, YourAllocator> yourlist;
// typeof mylist != type of yourlist (!!!)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow