Search code examples
c++stackdeque

pop_back() not working


I have the following main program that creates a Stack object, fills it with doubles and then pops them. The code files fine, but the pop_back() part does not seem to work, while s.back() does return the correct value. How is this possible?

#include "Stack.h"
#include <iostream>
#include <deque>
using namespace std;
int main() {

  Stack<double> s(0,0.0);

  // Write doubles into Stack
  int i ;
  for (i=0 ; i<15 ; i++) {

    s.push(i*i) ;

  }


  // Read doubles back from fifo
  while (!s.empty()) {
    double val = s.pop() ;
    std::cout << "Popping value " << val << " from stack" << std::endl ;

  }

  return 0 ;

}

My header file looks like this, where I have omitted parts which are not relevant to the question.

#ifndef STACK_H
#define STACK_H

#include <iostream>
#include <deque>  

template<class T>
class Stack {

public:  

  Stack(int len, T defval): s(len+1, defval) {

    return;
}

~Stack() {

    //delete [] s;
}

void push(T c) {

    s.push_back(c);

}

T pop() {

    return s.back();
    s.pop_back();  

}

private:   

  std::deque<T> s; //Array<T> s;  

};

#endif

Solution

  • T pop() {
        return s.back();
    //  ^^^^^
    
        s.pop_back(); // <- unreachable! 
    }
    

    When you return from a function, all the subsequent instruction will never be executed.


    Store s.back()'s result in a temporary variable instead:

    T pop() {
        auto back = s.back();
        s.pop_back();  
        return back;
    }