创建和 return 指向动态向量的函数的问题

Problem with function which create and return pointer to dynamic vector

我必须创建一个函数,该函数获取对 int 数组的引用作为参数之一。这个函数应该创建一个动态向量和 returns 它的指针。 当我编译这段代码时,我得到了错误:“没有匹配函数来调用 'func'”。 我不知道出了什么问题。 马上就想问一下我把内存中的dynamic vector去掉是正确的还是应该写的不一样?

#include <iostream>
#include <vector>
using namespace std;

vector<int> *func(int &, int);
int main() {
  const int arrSize = 5;
  int arr[arrSize] = {1, 3, 5, 7, 9};
  vector<int> *ptr_vec = func(arr, arrSize);
  delete ptr_vec;
}
vector<int> *func(int &arr, int size){
  auto *newVec = new vector<int>;
  for(int i = 0; i < size; i++) newVec[i].push_back(arr+i);
  return newVec;
}

提前致谢

函数的第一个参数是对 int 类型标量对象的引用

vector<int> *func(int &, int);

你需要写

vector<int> *func( const int *, int);

同样在for循环中你必须写

for(int i = 0; i < size; i++) newVec->push_back(arr[i]);

其实for循环是多余的。您的函数可能看起来更简单,例如

vector<int> * func( const int *arr, int size )
{
    return new std::vector<int> { arr, arr + size };
}

注意动态定义vector意义不大。可以通过以下方式声明和定义函数

vector<int> func( const int *arr, int size )
{
  return { arr, arr + size };
}