c++ 函数之间 传递向量_将向量传递给C ++中的函数

本文介绍了在C++中如何通过值和引用传递向量。当按值传递向量时,会创建向量的深拷贝,导致函数内部的修改不会影响原始向量,且效率较低。而按引用传递则不创建副本,直接操作原始向量,能及时反映变化,效率更高。何时使用值传递或引用传递取决于是否需要在函数中修改向量。
摘要由CSDN通过智能技术生成

c++ 函数之间 传递向量

Passing an argument can be of two types generally:

传递参数通常可以分为两种类型:

  1. Pass by value

    传递价值

  2. Pass by reference

    通过参考

In the case of passing a vector as a parameter in any function of C++, the things are not different. We can pass a vector either by value or by reference.

在C ++的任何函数中将向量作为参数传递的情况下,情况没有什么不同。 我们可以通过值或引用来传递向量。

In the following section, we will discuss when we should use what kind of passing and what's difference b/w them.

在下一节中,我们将讨论何时应该使用哪种传递方式以及它们之间的区别。

1)通过值传递向量 (1) Passing a vector by value)

Below is an example of passing the vector by value. In the below example, we have tried to figure out that if we pass a vector by value, whether local changes in the function reflects the original vector in main or not.

下面是通过值传递向量的示例。 在下面的示例中,我们试图弄清楚,如果我们按值传递向量,则函数中的局部更改是否会反映main中的原始向量。

Let's see the example first, then we will detail what happened and why.

首先让我们看一下示例,然后我们将详细说明发生了什么以及为什么。

#include <bits/stdc++.h>
using namespace std;

void print(vector<int> arr)
{ //paseed by value

    //printing the vector which has been passed
    cout << "In the print function...\n";

    cout << "Printing the array that has been passed by value\n";
    for (auto i : arr)
        cout << i << " ";
    cout << endl;

    cout << "chan
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值