c++ - 如何删除C++中给定矩阵中的特定行和列?

标签 c++ matrix search vector erase

我有一个vector的多维chars,并且我希望能够在命令中删除特定的列或行。例如,如果我有这个矩阵:

A B C D
L K T M
A M T N
删除第二列会将矩阵更改为
A C D
L T M
A T N 
然后,删除第三行会将矩阵更改为
ACD
LTM
我为此编写的代码当前针对行和列删除均返回错误:
void verticalSearch(vector< vector<char> >matrix, int startIndex, int lengthWord, string word)
{
    for(int k = 0; k < matrix[0].size() ; k++) // iterating for each column
    {
        for (int i = 0; i < matrix.size() - lengthWord + 1; i++) // for each row
        {
            char c;
            string s = "";
            for (int j = startIndex; j < startIndex + lengthWord; j++) // this startIndex is always 0
            {  // but this for loop stands for iterating in a length of given word

                c = matrix[i + j][k]; // adding given index of matrix to character c
                s += c;

            }
            
            if (s == word) // if a specific word is founded
            {
                
                matrix[0].erase(matrix[0].begin() + k); // delete this column but not working correctly
                cout << "Word is founded" << endl;
                printMatrix(matrix); // And print it 
            }
        }
    }
}
有人可以告诉我怎么了吗?

最佳答案

您具有行 vector ,因此要删除一列,必须从每一行中删除一个字符。您可以编写一个循环来执行此操作。例如。

for (int row = 0; row < matrix.size(); ++row)
    matrix[row].erase(matrix[row].begin() + k);
编辑
所以你的代码应该最终看起来像这样
if (s == word) // if a specific word is founded
{
    // delete a column            
    for (int row = 0; row < matrix.size(); ++row)
        matrix[row].erase(matrix[row].begin() + k);
    cout << "Word is founded" << endl;
    printMatrix(matrix); // And print it 
}

关于c++ - 如何删除C++中给定矩阵中的特定行和列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62744467/

相关文章:

c++ - 一起使用 std::thread 和 CUDA

c++ - 如何在 C++ 中将两个数组相加?

algorithm - 在访问每个单元格一次后到达矩阵中的目的地

Linux:获取文件和目录列表以及 MIME 信息

python - 在 8 拼图游戏中用 Python 计算曼哈顿距离

c++ - 在 Google UnitTest 中检测 glog 输出

c++ - libopkele 示例 openid

c++ - 在跳过对角线的 vector 上映射上三角矩阵

c++ - 在 C++ 中转置矩阵

android - 如何设置 Android 的 onSearchRequested() 样式;