【问题标题】:How to directly use vector as parameter in a function?如何在函数中直接使用向量作为参数?
【发布时间】:2022-01-06 00:12:39
【问题描述】:

我知道如何在使用新向量之前对其进行初始化,但是如何方便地将其用作函数中的参数? 比如我在初始化v1的时候,最后可以得到结果,但是当我使用v2的时候,却报错:cannot use this type name。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
    public:
    vector<int> Add(vector<int>&nums, int target)
    {       
        cout << nums[0] + target;
    }
};

int main(){
    Solution Sol1;
    vector <int> v1 {1,2,3};
    Sol1.add(v1, 8);
    Sol1.add(vector <int> v2{4,5,6}, 8);
}

此外,我尝试将 v2 更正为 Sol1.add(vector &lt;int&gt; {4,5,6}, 8); 但是,它显示错误:非常量引用的初始值必须是左值

【问题讨论】:

  • Add 承诺返回向量,但什么也不返回。永远不要忽略编译器错误。 C++ 是一种区分大小写的语言。你调用add,但是类没有这样的方法。 v2 的行不正确。
  • 在 S.M.提到如果您从 .Add(...) 行中删除 v2 并使 nums 成为 const ref 它应该可以工作(您不能将临时对象绑定到 l-value refs)

标签: c++ stl


【解决方案1】:

您遇到的问题与vector无关。

Sol1.add(vector<int> v2{4,5,6}, 8);

在这里,您似乎试图在此表达式的中间声明一个对象名称 v2,这在 C++ 中是无法做到的。

但是,您可以在其中创建一个未命名的临时对象,例如:

Sol1.add(vector<int>{4,5,6}, 8);

甚至:

Sol1.add({4,5,6}, 8);

但是现在你会面临一个不同的问题,就像你提到的那样:

非常量引用的初始值必须是左值

原因是您无法创建对临时对象的引用。要解决它,您可以通过更改 add 函数的签名将 vector 复制到您的函数中:

vector<int> add(vector<int> nums, int target)
{
  ⋮
}

但是,此解决方案需要将整个 vector 复制到函数中,因此如果您的 vector 很大,它可能会很慢。另一种方法是将签名更改为向量的 const 引用,该向量可以绑定到临时对象。不利的一面是,如果您希望这样做,您将无法修改函数内的对象:

vector<int> add(const vector<int>& nums, int target)
{
  ⋮
}

【讨论】:

    【解决方案2】:

    这是其中一种方式。 但是这样你将无法使用变量v2

    Sol1.add({4,5,6}, 8);
    

    更多详情请阅读Question

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 1970-01-01
      • 2014-09-03
      • 2023-03-19
      • 2015-12-12
      • 1970-01-01
      • 2013-02-22
      • 2020-10-27
      • 2020-02-17
      相关资源
      最近更新 更多