Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about vector iterator in template functions

I'm trying to learn the STL library and I'm having a weird problem. This code compiles perfectly:

void Show(vector<int> myvec) {     vector<int>::iterator it;     cout << "Vector contains:";     for( it = myvec.begin(); it < myvec.end(); it++)      {          cout << " " << *it;     }     cout << endl; } 

while this one gives me an error message at compile time:

template <class T>  void Show2(vector<T> myvec) {     vector<T>::iterator it;     cout << "Vector contains:";     for( it = myvec.begin(); it < myvec.end(); it++)     {          cout << " " << *it;     }     cout << endl; } 

The error is:

$ g++ hello.cpp hello.cpp: In function ‘void Show2(std::vector<T, std::allocator<_Tp1> >)’: hello.cpp:19: error: expected ‘;’ before ‘it’ hello.cpp:21: error: ‘it’ was not declared in this scope 

It seems a very simple mistake, but I couldn't find it.

like image 356
Rafael S. Calsaverini Avatar asked Mar 04 '11 11:03

Rafael S. Calsaverini


People also ask

How do you access the elements of a vector iterator?

You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively. using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector. push_back("a"); myvector.

Can we use iterator in vector?

Use an iteratorAn iterator can be generated to traverse through a vector. vector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence.

What is the distinct advantage of using iterator over simple for looks?

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.


2 Answers

You need to say typename vector<T>::iterator it.

On another note, you're passing vectors by value. That means the entire vector gets copied in the function call. void Show(vector<T> const &myvec) and using const_iterator would be wiser.

like image 132
Fred Foo Avatar answered Sep 28 '22 17:09

Fred Foo


You need this:

typename vector<T>::iterator it; 

This tells the compiler that vector<T>::iterator should be treated as a type, something it can't assume since iterator is dependent on what T is.

like image 24
Erik Avatar answered Sep 28 '22 16:09

Erik