hide on bush
hide on bush

Reputation: 47

How to pass stack to a function by pointer?

#include <iostream>
#include <string>
#include <stack>

using namespace std;

ostream& displayStack(ostream& os, stack<string> sstack)
{
    while(sstack.size() > 0)
    {
        os << sstack.top() << endl;
        sstack.pop();
    }
    return os;
}
int main()
{
    Stack<string> sstack;
    sstack.push('abc');
    sstack.push('bsa');
    sstack.push('csas');
    displayStack(cout, stack);
    return 0;
};

So there is my code. For perfecting my code, I want to pass 'sstack' to "displayStack" function by the pointer. How to do that base on my code?

Upvotes: 0

Views: 688

Answers (3)

Enrico
Enrico

Reputation: 120

Provided answers were correct. However, if it is needed for you to pass stack by pointer, you can do it this way:

std::ostream& displayStack(std::ostream& os, std::stack<std::string> *sstack)
{
    if (sstack != nullptr)
    {
        while (sstack->size() > 0)
        {
            os << sstack->top() << std::endl;
            sstack->pop();
        }
    }
    return os;
}
int main()
{
    std::stack<std::string> sstack;
    sstack.push("abc");
    sstack.push("bsa");
    sstack.push("csas");
    displayStack(std::cout, &sstack);
    return 0;
};

Upvotes: 0

John Park
John Park

Reputation: 1764

I recommend that you pass object by reference, but if you really want to pass std::stack by pointer,

#include <iostream>
#include <string>
#include <stack>

using namespace std;

ostream& displayStack(ostream& os, stack<string>* sstack)  // pass by pointer
{
    while (sstack->size() > 0)
    {
        os << sstack->top() << endl;
        sstack->pop();
    }
    return os;
}
int main()
{
    stack<string> sstack;
    sstack.push("abc");  // not ' but " for string
    sstack.push("bsa");
    sstack.push("csas");
    displayStack(cout, &sstack); // pass the address of sstack
    return 0;
};

Upvotes: 2

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122476

If you want to pass the stack by reference, so that changes in the function are reflected in the parameter in main, you should pass a std::stack<string>& if it is merely to avoid a copy then a const std::stack<string>&. Passing a pointer is only meaningful when a nullpointer is a valid parameter. However, it does not make sense to display a stack when there is no stack. Hence, pass by reference:

ostream& displayStack(ostream& os, stack<string>& sstack)
{
    while(sstack.size() > 0)
    {
        os << sstack.top() << endl;
        sstack.pop();
    }
    return os;
}

If you do not want to have modifications being reflected on the parameter then making a copy is ok. You cannot pop from a const stack<string>&, so you would have to make a copy anyhow.

Upvotes: 1

Related Questions