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

How can I delete specific rows and columns in a given matrix for C++?

本文关键字:C++ 何删除 删除      更新时间:2023-10-16

我有一个多维vectorchars,我希望能够根据命令删除特定的列或行。例如,如果我有这个矩阵:

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 
}
}
}
}

有人可以告诉我出了什么问题吗?

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

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 
}