Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

passing array (not vector) to function

I want to do this

void DoSomething (int arr[])
{
// do something
}

but instead of arr[] it’s std::array

void DoSomething (std::array <int> arr) // <--- incorrect way to declare an array
{
// do something
}

Using std::vector instead of std::array works, but I expect a workaround with std::array, since arr[] works just fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This works too

const int arrSize;
void DoSomething (std::array <int,arrSize> arr)
{
// do something
}

but again, I expect a way to do this without any extra declarations.

>Solution :

std::array is a template. If you want to accept a std::array of any size, your function will have to become a template as well, eg:

template <size_t N>
void DoSomething (std::array<int, N> arr)
{
    // do something
}

The compiler can then deduce N for you, based on whatever std::array you pass in.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading