如何删除给定矩阵中的特定行和列以进行C++?
How can I delete specific rows and columns in a given matrix for C++?
我有一个多维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
}
}
}
}
有人可以告诉我出了什么问题吗?
您有一个行向量,因此要删除列,您必须从每行中删除一个字符。您可以编写一个循环来执行此操作。例如
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++编译器通常会删除重复的库吗
- 从链接列表c++中删除一个项目
- C++如何通过用户输入删除列表元素
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 使用函数"remove"删除重复元素
- 如何从多映射中删除特定的重复项
- 运算符C++ "delete []"仅删除 2 个前值
- 删除指向指针的指针是运行时错误吗
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 将指针设置为"nullptr"并不能防止双重删除?
- 为什么示例代码访问IUnknown中已删除的内存
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- C++中的线程安全删除
- 擦除删除成语的性能增益从何而来