Reputation: 153
So based on other examples I've found, I'm led to believe that this would be the proper code to iterate over m_vect:
for(vector<T>::iterator it = m_vect.begin(); it != m_vect.end(); ++it)
However, upon attempting to compile, I get the following error on that line:
heap.h:167:6: error: need ‘typename’ before ‘std::vector<T>::iterator’ because ‘std::vector<T>’ is a dependent scope
Like I said, I copied and adapted the line from another piece of code, so I'm really not sure what I'm doing right and wrong. Any insight?
To clarify, this is in a template function, and I have declared 'template '. m_vect is of type vector. Aaaand I don't know how to display less than and greater than properly...
Upvotes: 0
Views: 123
Reputation: 5083
Thankfully in C++11 you can just have the compiler figure it out. The compiler already knows what m_vect is, so you can tell it:
for (auto it= m_vect.begin(); ( it != m_vect.end()) ; ++ it ) { }
But wait, there's more. In c++11 you can even just iterate over everything in m_vect
for (auto it : m_vect ) { }
Can you tell that I think iterating in C++03 was insane and I never saw anybody do it in real life, and in C++11 it is a thousand times better?
Upvotes: 6
Reputation: 103751
This appears to be in a template function, and vector<T>::iterator
is a type which is dependent on T
, which is a template parameter. Since templates can be specialized with unique definitions for any different type, the compiler has no way of being sure, until the template is actually instantiated, whether vector<T>::iterator
is a type, or a static member. If it is a static member, this does not make any sense, syntactically:
for(vector<T>::iterator it = m_vect.begin(); it != m_vect.end(); ++it)
What you need to do is tell the compliler that vector<T>::iterator
is a type. Use typename
for that:
for(typename vector<T>::iterator it = m_vect.begin(); it != m_vect.end(); ++it)
If you read your error, you can see that this is exactly what your compiler is telling you.
Upvotes: 1
Reputation: 2988
If you have amodern enough compiler, you can replace vector<T>::iterator
with auto
.
Else, find the correct type to replace the T
with for your vector.
Upvotes: 0
Reputation: 42825
This is something compilers are enforcing better now.
When you are using something derived from a template, you have to flag if it's being used as a type by adding typename
. Then if the compiler knows that (for some insane reason) vector<T>::iterator
is a method, it can immediately flag the error instead of heading into undefined behavior.
So just add typename
like the message says:
for(typename vector<T>::iterator it = m_vect.begin(); it != m_vect.end(); ++it)
Upvotes: 0
Reputation: 26395
T
needs to be an actual type. It should be the type of whatever is stored in the vector. Your for
loop looks correct. You declared m_vect
somewhere. The iterator needs the same time as whatever you declared m_vect
(plus ::iterator
of course).
Upvotes: 0