Home > Software design >  Understanding syntax of function parameter: vector<vector<int>> A[]
Understanding syntax of function parameter: vector<vector<int>> A[]

Time:07-19

I'm solving a question where a function is defined as following:

vector <int> func(int a, vector<vector<int>> B[]){
    // Some stuff
}

I'm confused about why the second parameter is not simply vector<vector<int>> B. Why the extra [] part in the parameter? Can someone clarify the meaning of this?

The vector, B, is populated by a similar code snippet:

vector<vector<int>> B[10]; 
while(num--){
    cin>>u>>v>>w;
    vector<int> t1,t2;
    t1.push_back(v);
    t1.push_back(w);
    B[u].push_back(t1);
    t2.push_back(u);
    t2.push_back(w);
    B[v].push_back(t2);
}

CodePudding user response:

Just as int foo(char str[]) is a function that takes a (c-style) array of characters, so int foo(vector<vector<int>> B[]) takes an array of vectors of vectors ... of integers. This means that it's three-dimensional data, requiring 3 indices to access the elements (fundamental data type; in this case, int), like B[i][j][k] = 5. Without the extra [] in the API it'd be two-dimensional data: a vector of vectors.

Note that int foo(char str[]) is equivalent to int foo(char str[5]) which is equivalent to int foo(char * str). In C we usually add the [] to a function declaration to imply that we expect to receive an array of those elements; while * is often used when we expect at most one element. Likewise, adding the number [5] is basically just a comment to the user of the code that they expect 5 elements, but the compiler won't enforce this. These conventions carry over to C when we use these c-style arrays ... which is rare.

With c-style arrays there's either going to be a maximum array size in the comments somewhere; or, more commonly, it's provided as an input. That may be what the first argument of the function is supposed to represent.

I agree with KungPhoo here that this API looks suspiciously bad. I'd expect bugs/bad performance just because the choices seem very amateurish. The c-style array means the function can't know where the end of the c-style array is - but the vectors mean that we give up some of the (niche) benefits of c-style simplicity (especially because they're nested!). It seems to be getting the worst of both worlds. But, perhaps, there may be a very niche justification for the API.

CodePudding user response:

B ist a static array (C-style) of 10 elements [0 .. 9]. It's not safe and this code is a terrible mess. Better use std::array<std::vector<str::vector<int>>, 10> B; instead to have index checking.

  • Related