2
#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?

Ron
  • 14,674
  • 4
  • 34
  • 47
CaesarK
  • 73
  • 1
  • 5
  • 4
    The same as you would with any other type. – Ron Jan 27 '18 at 21:50
  • 2
    Similar to the way you would define a function taking a reference to an array of any other type. – juanchopanza Jan 27 '18 at 21:50
  • I've tried to define it as void function(vector &gr); but its giving me an error. – CaesarK Jan 27 '18 at 21:53
  • *I've tried to define it as void function(vector &gr)* -- First, do you know that you've declared an array of `vector`? I ask this because I see a lot of new programmers make the mistake of declaring an array of vectors instead of just `std::vector gr;`. A `vector` itself is an "array" -- a dynamic array. – PaulMcKenzie Jan 27 '18 at 21:57
  • Wrong spelling in title: you probably want to pass by reference an array of vectors. It could be simpler to use `std::array` – Basile Starynkevitch Jan 27 '18 at 21:58
  • @PaulMcKenzie I've needed to implement Adjacency Lists in Graphs. I guess I need an array of vectors then? – CaesarK Jan 27 '18 at 22:02
  • Then use simply `std::array, 10> gr;`, as others have mentioned in the answers. – PaulMcKenzie Jan 27 '18 at 22:05
  • @CaesarK I always implemented adjacency lists with std::vector> – Edgar Rokjān Jan 27 '18 at 22:05
  • A vector is basically an object oriented array. Whenever you need and array, you can just use a vector (or maybe std::array<>). – Galik Jan 27 '18 at 22:10

3 Answers3

7

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
5
auto function(vector<int> (&gr)[10]) { ... }

It should be the right syntax to pass an array of std::vector<int> by reference.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
4

To pass an array of ten ints by reference you would use:

void foo(int (&gr)[10]);

Similarly, for an array of ten std::vectors it would be:

void foo(std::vector<int> (&gr)[10]);

That being said an array of vectors is somewhat unusual structure. Prefer std::array to raw arrays.

Ron
  • 14,674
  • 4
  • 34
  • 47