1

I am trying to create a member function that is supposed to replicate a stack by using a list. So I have to print the elements of the list in reverse order. I have a private list declared in my header file as:

class miniStackLT {
private:
    list<T> content;

I have the following code for that function:

template <typename T>
void miniStackLT<T>::PrintStack(){
    list<T>::iterator iter;
    iter = content.end();
    iter--;
    while (iter != content.end()) {
    cout << *iter << " | ";
    iter--;
    }
}

When I run the program I check the size of the so list and it tells me the correct number but when I print it, it prints the correct elements then I get an error that says the list iterator is not decrementable.

What is causing this error? I have tried messing around with the starting and ending points of the loop and the iterator, but I keep getting the error.

Edit: I have also used

template <typename T>
void miniStackLT<T>::PrintStack(){
    list<T>::iterator rit;
    for (auto rit = content.rbegin(); rit != content.rend(); ++rit){
        cout << *iter << " | ";
    }
}

But I still get the error.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Zack Sloan
  • 101
  • 3
  • 13

2 Answers2

4

You have two issues with your code. First while (iter != content.end()) will always be true since you are walking backwards away from content.end(). Second, even if you change it to while (iter != content.begin()) you will miss the first iterator in the list

The way to walk a list backwards is to use a reverse iterator. std::list has rbegin() and rend() which give you begin and end iterators but they traverse the list backwards so rbegin() gives you the last element in the list. to walk the list you would just use something like

for (auto rit = content.rbegin(); rit != content.rend(); ++rit)

You could also one up that and use a ranged based for loop. Using the code from here by Prikso NAI you would be able to have

for (const auto& e : reverse(content))
    std::cout << e << " | ";
Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
0

At some point you reach content.begin(). After that, it is not decrementable.

Changing your condition to while (iter != content.begin()) should fix this.

But you should consider using rbegin() and rend() and a reverse iterator.

Rosme
  • 1,049
  • 9
  • 23