Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a new array with specified values?

Tags:

c++

Is there a way to write the following function code

int* returnFilledArray() {
 int* arr = new int[2];
 arr[0] = 1;
 arr[1] = 2;
 return arr;
}

somehow like that? (create and fill the array as one liner).

int* returnFilledArray() {
 return new int {1,2};
}

if have tried various combinations, but I allways get some syntax errors, so when if it's possible I would be thankful for a detailed explanation.

like image 830
Nicola Coretti Avatar asked Jul 15 '26 05:07

Nicola Coretti


2 Answers

Yes..

std::vector<int> returnFilledArray()
{
  int a[] = {1, 2};
  return std::vector<int>(a, a+2);
}
like image 93
Nim Avatar answered Jul 17 '26 17:07

Nim


You cannot do what you are trying to do in Standard C++ (03) without using special libraries.

like image 36
John Dibling Avatar answered Jul 17 '26 18:07

John Dibling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!