我想知道以下两个函数中哪一个在时间和空间上最有效。它们都检查堆栈中是否存在某个元素。第一个使用传值机制,而第二个使用传递引用。我可能是错的,但我认为传值机制隐式地复制了参数,而在pass-by-ref中,我们明确地执行它。C++中传递值与传递引用之间的区别
第一版通过按值:
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;
}
第二版本通过按引用:
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;
}
你的假设大部分是正确的。按引用传递的效率与传递指向对象的指针效率相同。 –
此代码看起来很熟悉..... :) –