Home > other >  Problem with function which create and return pointer to dynamic vector
Problem with function which create and return pointer to dynamic vector

Time:01-13

I have to crate a function which gets a reference to int array as one of arguments. This function should creates a dynamic vector and returns its pointer. When I compile this code I got err: "No matching function for call to 'func'". I have no idea what's wrong. Immediately, I would like to ask if I removed the dynamic vector from the memory correctly or should I write it differently?

#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;
}

Thanks in advance

CodePudding user response:

The first parameter of the function is a reference to a scalar object of the type int

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

You need to write

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

Also in the for loop you have to write

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

In fact the for loop is redundant. Your function could look simpler as for example

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

Pay attention to that there is no great sense to define the vector dynamically. The function can be declared and defined the following way

vector<int> func( const int *arr, int size )
{
  return { arr, arr   size };
}
  •  Tags:  
  • Related