如何修改向量内的元素
How can I modify elements inside vectors?
我试图修改向量内的元素。在我更改数组中的某个块并再次显示它之后,它不会显示新的值,而是保留以前的输出。我做错了吗?
////////////////////////////////////////////////////
// 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
按值取maze
参数。它对vector
所做的任何更改都是对函数内的本地副本进行的,当函数退出时,该副本将被销毁。更改函数,使其通过引用获取maze
参数。
void updateMouse( vector<vector<char>>& maze, const int &mouse_row, const int &mouse_col ) {
// ^^^
updateMouse
函数也可以简化为
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';
}
}
}
你应该传递你的vector
作为一个引用(或指针):
void updateMouse( vector< vector<char> > & maze, const int &mouse_row, const int &mouse_col ) {
否则你要做的就是改变迷宫的副本
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C