How to pass 2-D vector to a function in C++?

后端 未结 3 1848
独厮守ぢ
独厮守ぢ 2020-12-29 11:05

If it is passed, is it passed by value or by reference?

void printMatrix(vector> *matrix);

...

vector> matr         


        
3条回答
  •  攒了一身酷
    2020-12-29 11:56

    Well, first of all, you're creating it wrong.

    vector> matrix1(3, vector(3,0));
    

    You can pass by value or by reference, or by pointer(not recommended). If you're passing to a function that doesn't change the contents, you can either pass by value, or by const reference. I would prefer const reference, some people think the "correct" way is to pass by value.

    void printMatrix(const vector> & matrix);
    
    // or
    void printMatrix(vector> matrix);
    
    // to call
    printMatrix(matrix1);
    

提交回复
热议问题