Search code examples
c++c++11c++14

How to pass an array of vectors by reference?


#include <vector>
using std::vector;

int main(void)
{
    vector<int> gr[10];

    function(gr);
}

How should I define that function calling by reference rather than by value?


Solution

  • For pass by reference:

    void foo( vector<int> const (&v)[10] )
    

    Or sans const if foo is going to modify the actual argument.


    To avoid the problems of the inside-out original C syntax for declarations you can do this:

    template< size_t n, class Item >
    using raw_array_of_ = Item[n];
    
    void bar( raw_array_of_<10, vector<int>> const& v );
    

    However, if you had used std::array in your main function, you could do just this:

    void better( std::array<vector<int>, 10> const& v );
    

    But this function doesn't accept a raw array as argument, only a std::array.