Stack Container Function

closed account (S3TkoG1T)
Hello!

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)
        {
            return true;
        }
        else if (s.top() != val)
            s.pop();
    }
    return false;
}


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
   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 << 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

Thank you!
Last edited on
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)
closed account (S3TkoG1T)
hm! Let me try it :)
closed account (S3TkoG1T)
OMG IT WORKED! THANK YOU! Here's the change <3

1
2
3
4
5
6
7
8
9
10
template <typename T>
bool contains(stack<T> &s, const T &val) {
         while(!s.empty()) {
         return true;
         }
         else if (s.top() != val)
           s.pop();
         }
        return false;
}
Pop will remove the element from the stack,

1
2
3
4
5
 while (!ss.empty())
    {
                ss.pop();
                cout << ss << endl;
        }


This will clear your stack i believe.

hi,

I am new in this forum , I have same problem, thank for your solution,this site will be very useful to C, C++ beginners
Last edited on
closed account (S3TkoG1T)
Glad it benefited you too, thanks all! :)
Topic archived. No new replies allowed.