Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c+中传递值和传递引用之间的差异+;_C++_Pass By Reference_Pass By Value - Fatal编程技术网

C++ c+中传递值和传递引用之间的差异+;

C++ c+中传递值和传递引用之间的差异+;,c++,pass-by-reference,pass-by-value,C++,Pass By Reference,Pass By Value,我想知道以下两个函数中哪一个在时间和空间方面效率最高。它们都检查堆栈中是否存在某个元素。第一个使用值传递机制,而第二个使用引用传递机制。我可能错了,但我认为pass-by-value机制隐式复制参数,而在pass-by-ref中我们显式复制参数 按值传递的第一个版本: template<class T> bool find (stack<T> source, T value) { while (!source.isEmpty() && sour

我想知道以下两个函数中哪一个在时间和空间方面效率最高。它们都检查堆栈中是否存在某个元素。第一个使用值传递机制,而第二个使用引用传递机制。我可能错了,但我认为pass-by-value机制隐式复制参数,而在pass-by-ref中我们显式复制参数

按值传递的第一个版本:

 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;
}
模板
布尔查找(堆栈源,T值)
{
而(!source.isEmpty()&&source.top()!=value)
source.pop();
如果(!source.isEmpty())
返回true;
返回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;
模板
布尔查找(常量堆栈和源,T值)
{
堆栈温度=源;
而(!temp.isEmpty()&&temp.top()!=值)
temp.pop();
如果(!temp.isEmpty())
返回true;
返回false;

}

如果仍要在函数内部创建本地副本,请使用“传递值”。它更简单,更简单通常是好的

另外,当您返回
bool
结果时,通常不需要
if
语句

return !source.isEmpty();

你的假设基本上是正确的。通过引用传递的效率与向对象传递指针的效率相同。此代码看起来很熟悉……:)在复制版本中也有一些复制省略的范围。