开发者

Return a new array with specified values?

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 开发者_StackOverflow社区a detailed explanation.


Yes..

std::vector<int> returnFilledArray()
{
  int a[] = {1, 2};
  return std::vector<int>(a, a+2);
}


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


C++ 0x supports initializer lists - is that an option for you?


I had answered similar question here. You can use following technique:

template<typename T, T _0, T _1, T _2, T _3, T _4> struct Array
{
  static T* Init (T *a)
  {
    a[0] = _0;
    a[1] = _1;
    a[2] = _2;
    a[3] = _3;
    a[4] = _4;
    return a;
  }
};

int* fun ()
{
  return Array<int, 1, 2, 3, 4, 5>::Init(new int[5]);
}


In C++0x:

#include <vector>
std::vector<int> returnFilledArray()
{
  return std::vector<int> {1,2} ;
}


If you're not allowed to use std::vector, then you can try a macro:

#define FILLED_ARRAY(name) int name[] = {1, 2}


I was able to do similar task using

int *ptr = new int[]{1, 2, 3};

you can then return from your function as

return (new int[]{1, 2, 3});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜