Kapil Bhandari Kapil Bhandari - 3 months ago 9
C++ Question

c++ iterators to list in a generic functions

Here is the code , where i am trying to simulate Queue using STL lists , the class is

template <class T>
class myqueue{
list<T> m;
public:
void enqueue(T item);
T dequeue();
void display();
};


Here is the implementation of display function where I want to display the contents of the list
m
, with the use of iterators .

template <class T>
void myqueue<T>::display(){
// list<T>::iterator it;
for (auto it = m.begin(); it < m.end(); it++)
std::cout << *it;
}


and I am continuously getting the error Need help on this, This has been resolved I should have used
!=
instead of
<
in the For Loop

EDIT :

template <class T>
void myqueue<T>::display() {
// list<T>::iterator it;
for (list<T>::iterator it = m.begin(); it < m.end(); it++)
std::cout << *it;
}


and I am getting the error as

"31:13: error: need 'typename' before 'std::list<T>::iterator' because 'std::list<T>' is a dependent scope"


if I use keyword
auto
it works fine. What is the reason behind it ??

Answer
for(auto it = m.begin();it<m.end();it++)

should be

for (auto it = m.begin(); it != m.end(); it++)

or simply:

for (const auto& e : m)