How to pass std::array as a parameter irrespective of its size.?

I am trying to make myself more familiar with C++11. One of the new features is std::array which is declared as follows

1
2
3
4
5
6
#include <array>

int main()
{
std::array<int,6> Numbers = {1,2,3,4,5,6};
}


With this kind of array, you have to specify the size as part of it's type. As a result of this, I'm not sure how to write the prototype for a function that should be able to work with a std::array of any size as its parameter. How would one go about this?

Perhaps this code will explain it better
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <array>

int sum(std::array<int,What do I write here so that it doesn't matter what size the array is>)

int main()
{
   std::array<int,6> Numbers = {1,2,3,4,5,6};
}

int sum(std::array<int,..and here> Numbers)
{
   int total;
   for(int i=0;i<Numbers.size();i++)
   {
      total+=Numbers[i];
   }
       return total;
} 
First of all there is standard algorithm std::accumulate which allows to calculate the sum of array's elements.

int sum = std::accumulate( Numbers.begin(), Numbers.end(), 0 );

Also class std::array has member function data() (if I am not mistaken) that returns address of the first elemennt of the array.

So you can write

int sum( int *a, size_t n );
and call it sum( Numbers.data(), Numbers.size() );

And at last you can define your function sum as a template function specially for a parameter of type std::array.
Last edited on
Topic archived. No new replies allowed.