Problem with stack of strings
May 11, 2014 at 11:04pm UTC
So I have code that uses a stack to check whether a value exists in the stack. When the stack is a stack of
int
, it properly tells me whether a number is in the stack for numbers 10 and up but single digit numbers always return false. Additionally the stack of strings always returns
false
. What is going wrong?
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
ostream &operator <<(ostream &os, stack<T> &s) {
stack<T> hold;
os << "[" ;
while (!s.empty()) {
T t = s.top();
hold.push(t);
s.pop();
os << t << (!s.empty() ? ", " : "" );
}
os << "]" ;
while (!hold.empty()) {
s.push(hold.top());
hold.pop();
}
return os;
}
template <typename T>
bool contains(stack<T> s, T val){
for (int i = 0; i < s.size(); i++){
if (s.top() == val) return true ;
s.pop();
}
return false ;
}
int main() {
cout << boolalpha;
stack<int > si;
for (int i = 0; i < 20; i++)
si.push(i);
cout << "si contains 15: " << contains(si, 15) << endl;
cout << "si contains 23: " << contains(si, 23) << endl;
cout << si << endl;
while (!si.empty()) {
si.pop();
cout << si << endl;
}
const int ARR_SIZE = 4;
string arr[ARR_SIZE] = {"cat" , "dog" , "cow" , "elephant" };
cout << endl;
stack<string> ss;
for (int i = 0; i < ARR_SIZE; i++)
ss.push(arr[i]);
cout << "si contains \"dog\": " << contains(ss, string("dog" )) << endl;
cout << "si contains \"muskrat\": " << contains(ss, string("muskrat" )) << endl;
cout << ss << endl;
while (!ss.empty()) {
ss.pop();
cout << ss << endl;
}
return 0;
}
May 11, 2014 at 11:24pm UTC
The loop inside the contains function does not check all elements in the stack.
First iteration: i=0, s.size()=4
Second iteration: i=1, s.size()=3
The third iteration doesn't happen because then i=2 and s.size()=2
May 11, 2014 at 11:34pm UTC
Thanks, I fixed it.
Topic archived. No new replies allowed.