+ 1
Templates and Vector<type>::iterator
Please help on code below, is there some way i can use a generic type iterator? Or does the type have to be hard coded in? https://code.sololearn.com/cAd1gDN6V5N8/?ref=app
15 Réponses
+ 11
Robert Atkins
You need to say
typename vector<T>::iterator it
https://code.sololearn.com/cOezf320aryW/?ref=app
+ 5
Hello!
I think a detailed explanation is necessary here..
First :
Why typename is necessary?
Because iterator is a type contained inside vector<T>
A vector<U> will have a different iterator type.
In short to use a nested class from outside you need typename.
"Inside a declaration or a definition of a template, typename can be used to declare that a dependent qualified name is a type."[cppreference]
second:
[ ] (auto x){//...};
Is the C++14 generic lambda and yes ~ swim ~ , it's life safer and allows you to write generics and reusable lambdas! 👍
+ 5
Yes correct.
Vector is a Standard Template class this means that when you create a vector<T> the compiler generates code for vector <T> using the template system .
A vector<U> is a different type/class..
The vector class contains a nested class clalled iterator and it's generated just like the whole vector.
So a std::vector<T>::iterator (note the scope resolution between vector and iterator ) is a type dependant on std::vector<T> type.
+ 5
Nice to help! :)
+ 4
Lambda : Constructs a CLOSURE : an unnamed function object capable of capturing variables in scope.[cppreference]
Hence a function object can be treated as a variable (assigned, passed to function.. )
The type of a lambda "doesn't exists" it is created for every lambda expression so you need "auto" to get it..
auto myLambda = [ ](parameters){ //job...;}; <= the typical end ;};
Link: https://en.cppreference.com/w/cpp/language/lambda
auto is a placeholder type specifier.
In short it automatically deduce the right type.
+ 3
AZTECCO thanks alot for the detailed explanation, i definitely feel like i have a better understanding of how to utulize the STL!
+ 2
AZTECCO i think I understand, so basically when you use a template, and I'm assuming this applies to any class that utulizes a type specifier<>, when accessing a member that constructs a new object utulizing type T, the generic type T doesn't supply enough information for a proper iterator to be constructed by itself, so we use typename to specify that we need type T's specific iterator to be returned. Is this a correct way to view this? Or am i way off base?
+ 1
GAWEN STEASY ~ swim ~ thank you two for all the help, also thanks for going the extra mile swim! I really need to start learning lambda, i tried learning them in java but i definitely dont even have a foundational knowledge of them other than understanding what they are.
+ 1
thats from C++11 right?