Question

I'm wondering which of the following two functions is the most efficient in terms of time and space. They both check for the existence of a certain element in the stack. The first one uses pass-by-value mechanism, while the second one uses pass-by-reference. I may be wrong but I think that the pass-by-value mechanism copies the parameters implicitly, while in the pass-by-ref we do it explicitly.

First Version passed-by-value:

 template<class T>
 bool find (stack<T> source, T value)
{
    while (!source.isEmpty() && source.top() != value)
        source.pop();

    if (!source.isEmpty())
        return true;

    return false;
}

Second Version passed-by-reference :

template<class T>
bool find (const stack<T> &source, T value)
{
 stack<T> temp = source; 
while (!temp.isEmpty() && temp.top() != value)
    temp.pop();

if (!temp.isEmpty())
     return true;

return false;

}

Was it helpful?

Solution

If you're going to be making a local copy inside the function anyway, use pass by value. It's simpler, and simpler is usually good.

P.S. when you're returning a bool result you don't usually need an if statement for it.

return !source.isEmpty();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top