Can I initialise the size(both row and col) of a vector of vectors in the function declaration in c++?

Viewed 73

For example:

void fillVector(std::vector<<std::vector<int> >& grid(int row, std::vector<int(int col));

int main(){

    std::vector<<std::vector<int> > grid(4, std::vector,int>(2));
    fillVector(grid);

    return 0;
}

Is this a possibility or am I completely off the mark?

1 Answers

std::vector is used when you don't know the sizes at compile time. When you do, use std::array instead:

void fillArray(std::array<std::array<int, 2>, 4>& grid);

int main(){

    std::array<std::array<int, 2>, 4> grid={}; //initialize with zeros, like vector default constructor
    fillArray(grid);

    return 0;
}

Another advantage of std::array is that it does not use dynamic memory allocation.

Related