I need some help with my function: (Everything is compiled successfully btw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template <typename T>
bool contains(stack<T> &s, const T &val)
{
for(int i = 0; i < s.size(); i++)
{
if (s.top() == val)
{
returntrue;
}
elseif (s.top() != val)
s.pop();
}
returnfalse;
}
I need it to practically search for at least two values in the container.
Once implementing it in the main:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
constint 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 << ss << endl;
while (!ss.empty())
{
ss.pop();
cout << ss << endl;
}
cout << "ss contains "dog": " << contains(ss, string("dog")) << endl;
The output should be:
ss contains "dog": true
Instead I am getting:
ss contains "dog": false
Can anybody help me see why this is?? I have tried everything I can possibly think of! My contains function is not properly working and I can't figure out why
The problem is that with your for loop right there, the value of i is constantly increasing, while the value of s.size() is constantly decreasing (you're popping elements off the stack), so the two will meet somewhere in the middle (which is where the loop ends because i < s.size() is no longer true), which isn't exactly what you want because that would mean that about half of the stack never gets touched.
Replace your for with a while (!s.empty()) and you should be fine. (I hope)