-3

I'd like to pass an C++ std::array defined as

array<int,100> arrayName

to another function, but I don't want to specify there the size, so I can easily change the size only at creation of the array.

How do I write this? I can't write

function(array<> arrayName)

as I would do with an char array...

Kind regards, iova.

iova
  • 3
  • 4

2 Answers2

5

If you know the array size in compile-time, as is implied by your usage of std::array, then you have templates to the rescue. To restrictively support std::arrays of int of different sizes you can do this:

#include <array>

template <size_t N>
void ArrayFunc(std::array<int, N> arr)
{
    // Do something with `arr`
}

int main()
{
    std::array<int, 10> arr10;
    std::array<int, 20> arr20;

    ArrayFunc(arr10);
    ArrayFunc(arr20);

    return 0;
}

Note the passing by value of the arr parameter of ArrayFunc(), a thing you should consider whether it is desired or not -- I was just following your example (in pseudo) in your question. If you don't really want to copy the entire std::array for each function call then you can do either:

template <size_t N>
void ArrayFunc(std::array<int, N>& arr)

or

template <size_t N>
void ArrayFunc(const std::array<int, N>& arr)

Depending on whether you will be modifying arr in the function or not.

Geezer
  • 5,600
  • 18
  • 31
0

Use of vector will be good choice as it dynamic in nature but be carefull as it consume more space it gets double after initial value like if vector u declare of 10 after 10 it will GET 20 after 20 get 30 every it will grow by 10 . And still u dont want u use it u can create your own dynamic array by using two array and using some pointer .

keshav keyal
  • 9
  • 1
  • 3