简体   繁体   中英

How can I modify elements inside vectors?

I'm trying to modify the elements inside a vector. After I change a certain block in an array and display it again, it won't show the new values but instead, retain the previous output. Am I doing it wrong?

////////////////////////////////////////////////////
// This displays the array/maze
////////////////////////////////////////////////////
void displayMaze( vector< vector<char> > &maze ) {
    for( int i = 0; i < ROW; i++ ) {
        for( int j = 0; j < COL; j++ ) {
            cout << "[" << maze[ i ][ j ] << "] ";
        }
        cout << endl;
    }
}

////////////////////////////////////////////////////
// This is where I change a certain element
////////////////////////////////////////////////////
void updateMouse( vector< vector<char> > maze, const int &mouse_row, const int &mouse_col ) {
    for( int row = 0; row < ROW; row++ ){
        for( int col = 0; col < COL; col++ ) {
            if( ( row == mouse_row ) && ( col == mouse_col ) ) {
                maze[ row ][ col ] = 'M';
                break;
            }
        }
    }
}

updateMouse takes the maze argument by value . Any changes it makes to the vector are made to the local copy within the function, which will be destroyed when the function exits. Change the function so that it takes the maze argument by reference .

void updateMouse( vector<vector<char>>& maze, const int &mouse_row, const int &mouse_col ) {
//                                   ^^^

The updateMouse function can also be simplified to

void updateMouse( vector<vector<char>>& maze, int mouse_row, int mouse_col ) {
    if(mouse_row < maze.size()) {
        if(mouse_col < maze[mouse_row].size()) {
            maze[mouse_row][mouse_col] = 'M';
        }
    }
}

You should be passing your vector as a reference (or pointer):

void updateMouse( vector< vector<char> > & maze, const int &mouse_row, const int &mouse_col ) {

Otherwise what you do is you change the copy of the maze

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM