为什么以及何时通过引用传递向量?

发布于 2025-01-09 08:20:46 字数 375 浏览 3 评论 0原文

我有一个问题,为什么要通过引用传递向量或字符串。为什么要通过引用传递值? 让我们举个例子:- 假设我想在函数中传递一个向量,那么我会编写下面的代码:-

void fun(vector<string/int>v){
......
......
}

所以有时它会给出正确的输出,但有时它会给出错误的输出。

但是当我使用:-

void fun(vector<string/int> & v){
......
......
}

那么错误的输出就会变成正确的 那么请告诉我何时使用 & 以及为什么?

提前谢谢你...

I have a question that why to pass vector or string by reference. simply why to pass a value by reference?
let's take a example :-
suppose I want pass a vector in function then I'd write below code:-

void fun(vector<string/int>v){
......
......
}

so sometime it gives correct output but sometime it gives wrong.

but when I use:-

void fun(vector<string/int> & v){
......
......
}

then wrong output turns right
so tell me when to use & and why ?

thank u in advance...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉城メ夜风 2025-01-16 08:20:46

为什么以及何时通过引用传递向量?

当需要间接寻址并且不需要指针时,应该使用引用。

您可能需要间接

  • 如果您需要避免不必要的复制,
  • 。您打算就地修改对象。
  • 您需要观察对象的身份(内存地址)。

因为:

  • 传递值可能需要复制,而使用间接可以避免这种情况。复制可能会很昂贵,例如向量的情况。
  • 如果没有间接,您就无法就地修改参数。
  • 如果参数是一个值,那么它与参数不是同一个对象,因此它们将具有不同的标识。
  • 引用不能为空,这使得它们比指针更容易使用,因此在不需要可为空时更可取。

Why and when to pass vector by reference?

You should use a reference when you need indirection, and you don't need a pointer.

You may need indirection if

  • You need to avoid unnecessary copying.
  • You intend to modify the object in-place.
  • You need to observe identity (memory address) of the object.

Because:

  • Passing a value potentially requires copying that may be avoided by using indirection. Copying can be expensive, such as in the case of vectors.
  • Without indirection, you cannot modify the argument in-place.
  • If the parameter is a value, then it isn't the same object as the argument and hence they will have a different identities.
  • References cannot be null, which makes them easier to use than pointers and hence preferable when the nullability isn't needed.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文