1

I was trying to use multidimensional vector and change the values of row and column.

#include<iostream>
#include<vector>
using namespace std;

void changerow(vector<vector<int> > A, int row, int M, int P){
    for(int j = 0; j < M; j++){
        (A[row - 1])[j] = ((A[row - 1])[j] + P) % 10;

    }
}

void changecolumn(vector<vector<int> > A, int column, int N, int P){
    for(int i = 0; i < N; i++){
        (A[i])[column - 1] = ((A[i])[column - 1] + P) % 10;
    }
}

int main(int argc, char* argv[])
{
    int T, N, M;
    cin >> T >> N >> M;
    if((T >= 1 && T <= 10) && (M >= 1 && M <= 100) && (N >= 1 && N <= 100)){
        // Logic of the program
        vector<vector<int> > A(N, vector<int>(M));

        for(int i = 0; i < N ; i++){
            for(int j = 0; j < M; j++){
                cin >> (A[i])[j];
            }
        }
        changerow(A,2,M,3);
        for(int i = 0; i < N ; i++){
            for(int j = 0; j < M; j++){
                cout << A[i][j];
            }
        }
    }
    return 0;
}

I don't know how would pass the address of the vector in order to change the element, since only the local copy of the vector gets passed. I am currently reading Thinking in C++ Volume 1 but its not elaborate. Kindly let me know a good source for learning the use of vectors in C++.

Sumit Gera
  • 1,249
  • 4
  • 18
  • 34

1 Answers1

2

Currently, you are passing the vector by value, which means that the callee gets a copy of the vector.

If you wish the changes that the callee makes to be visible to the caller, you need to pass the vector by reference. This is done like so:

void changecolumn(vector<vector<int> >& A, int column, int N, int P){
                                      ^ THIS

For a discussion, see Pass by Reference / Value in C++

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • I knew the concept of reference but I did not know the syntax to be used with `vector`. Can you also recommend any source for learning vectors? – Sumit Gera Mar 23 '13 at 08:53
  • @mozart: I liked Accelerated C++ when it came out, but I suppose it is a little dated now. I am not sure what current introductory books there are out there. – NPE Mar 23 '13 at 09:03
  • @mozart, "Effective STL" by Scott Meyers is a great source of info on C++ standard library, including vectors. It's a bit difficult sometimes, but if you fight through, you'll know everything you need. – Steed Mar 23 '13 at 09:03
  • @mozart, still you really need to get more fluent with references, so you can pick any good book from this list http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list, if your book doesn't cover the subject enough. – Steed Mar 23 '13 at 09:06