In some legacy code I see the following:
class myClass : public CObject
{
DECLARE_DYNAMIC(myClass)
public:
void myClassMethod() const;
....
}
std::vector<const myClass*> vMyClass;
...
for (const myClass *const* Q = vMyClass.begin(); Q != vMyClass.end(); Q++)
(*Q)->myClassMethod();
I don't understand what const is doing here. (I can't search for it, either in this forum or in Google, without the asterisks being stripped off, so searching for an explanation is useless.)
What I do know is that this code generally assumed that vector.begin() returns a pointer rather than an iterator. So I tried rewriting the for loop as:
std::vector<myClass*>::iterator Q;
for (Q = vMyClass.begin(); Q != vMyClass.end(); Q++)
(*Q)->myClassMethod();
But I get the following error from the Visual Studio 2003 C++ compiler:
error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::vector<_Ty>::iterator' (or there is no acceptable conversion) with [ _Ty=myClass * ]
I don't understand what's going wrong here... In another part of the code I have:
std::vector<myOtherClass> vMyOtherClass;
...
std::vector<myOtherClass>::iterator Z;
for (Z = vMyOtherClass.begin(); Z != vMyOtherClass.end(); ++Z)
...
this compiles cleanly. Any ideas why I get the error on the vMyClass loop or what to do about it? Any idea what const is doing?
New Information
Originally, I had copied the vector definition incorrectly. Now that it's fixed (above), I see that the iterator was missing a const. It should read:
std::vector<const myClass*>::iterator Q;
But when I made this fix in my code, the error message switched from the call to vector.end() to vector.begin():
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>::const_iterator' (or there is no acceptable conversion) with [ _Ty=const myClass * ]
I don't get how it could work for vector.end() with operator !=, yet be wrong for vector.begin() with operator =...?