Hi, how do I print the value being popped or being pushed just to follow what's going on? I get windows error(below). I can print nStack.top() fine. Just not the others.
#include<iostream>
#include<stack>
usingnamespace std;
void fooPush(stack<int>&nStack, int val)
{
nStack.push(val);
}
fooPop(stack<int>&nStack)
{
nStack.pop();
cout<<nStack.top()<<endl;
}
int main()
{
stack<int>nStack;
fooPush(nStack, 5);
fooPush(nStack,10);
fooPush(nStack,15);
fooPop(nStack);
nStack.top() -=2;
cout<<nStack.top()<<endl;
//std::cout<< "nStack.top() is now " << nStack.top() << '\n';
}
error:..\src\main.cpp:14:6: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'void')
cout<<nStack.pop();
^
The code you provided doesn't compile so I don't know how you're getting any output.
In function 'int main()': 23:19: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' 4:6: note: in passing argument 2 of 'void fooPush(std::stack<int>&, int&)' 24:20: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' 4:6: note: in passing argument 2 of 'void fooPush(std::stack<int>&, int&)' 25:20: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' 4:6: note: in passing argument 2 of 'void fooPush(std::stack<int>&, int&)' 26:20: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' 4:6: note: in passing argument 2 of 'void fooPush(std::stack<int>&, int&)'
Once you fix the compile error it should work as you expect.
You could have also fixed the problems by passing by value instead of by reference. void fooPush(std::stack<int>&nStack, int val) // Note, passing val by value instead of by reference.
Why did pass by value work for this code as opposed by pass by reference. I know it should be obvious, but its not for me. I have passed by reference so much, I have forgotten the scenarios in which pass by value is more acceptable. Thx
In function 'int main()': 23:19: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
A couple of things stand out when I read this error, first is that word const. Whenever I see this word in an error message I start looking for const correctness problems. The next thing that stands out is that "rvalue" instead of "lvalue". I believe it comes down to you can't create a reference to a const rvalue.