Reputation: 419
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;
}
Upvotes: 0
Views: 2454
Reputation: 308158
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();
Upvotes: 7