我有一个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/