Raaj
Raaj

Reputation: 57

Passing an std::array as an argument in C++

I want to pass an std::array as an argument to a function, and I cannot find the correct way.

I am not talking about normal C array (e.g. int arr[2]={1,3};). I am talking about std::array class, available from C++ 11.

Example code:

#include <iostream>
#include <array>

using namespace std;

class test
{
   void function(array<int> myarr)
   {
      // .......some code..........
   }
};

How do I pass an std::array to a function, as std::array takes two template arguments: std::array<class T, std::size_t N>, but while passing it as an argument I do not want to specify the size?

Upvotes: 2

Views: 2068

Answers (2)

Gerhard Stein
Gerhard Stein

Reputation: 1563

You could use an approach like:

#include<array>
using namespace std;

template <size_t N>
class test
{
    void function(const array<int, N> & myarr)
    {
        /* My code */
    }
};

But keep in mind that std::array is not a dynamic array. You have to know the sizes at compile time.

If you get to know the sizes later at runtime of your program you should consider using std::vector instead:

#include<vector>

using namespace std;

class test
{
    void function(const vector<int> & myvec)
    {
        /* My code */
    }
};

In that variant you don't need to pass the size at all.

Upvotes: 0

Raz Rotenberg
Raz Rotenberg

Reputation: 609

Not knowing the second template argument to std::array<> means your test class should be templated as well.

template <std::size_t N>
class test
{
    void function(const std::array<int, N> & myarr)
    {
        // ...
    }
};

By the way, it's better to pass myarr as const &.

Upvotes: 4

Related Questions