C++如何根据一维int向量的0值删除2D vector对应行和列
解决方案
要实现同步删除对应索引的列,可按照以下逻辑调整代码,该方案适配100×100规模的矩阵无任何性能压力:
核心逻辑
- 提前基于原始
boundaryConditions收集需要保留的列索引,避免边遍历边删除导致的索引偏移问题 - 你现有的行删除逻辑可直接保留
- 列删除只需逐行过滤掉不需要的列元素即可
完整修改后代码
#include <iostream> #include <vector> #include <iomanip> int main() { std::vector <int> boundaryConditions = { 0,1,1,1,0,0 }; std::vector <std::vector<double>> matrix = { {1.46371e+07, 1.46371e+07, -1.46371e+07, -1.46371e+07, 0, 0}, {1.46371e+07, 5.60371e+07, -1.46371e+07, -1.46371e+07, 0, -4.14e+07}, {-1.46371e+07, -1.46371e+07, 5.60371e+07, 1.46371e+07, -4.14e+07, 0}, {-1.46371e+07, -1.46371e+07, 1.46371e+07, 1.46371e+07, 0, 0}, {0, 0, -4.14e+07, 0, 4.14e+07, 0}, {0, -4.14e+07, 0, 0, 0, 4.14e+07} }; // 第一步:提前收集需要保留的列索引(原始索引中boundaryConditions为1的位置) std::vector<int> keep_cols; for (int k = 0; k < boundaryConditions.size(); k++) { if (boundaryConditions[k] == 1) { keep_cols.push_back(k); } } // 第二步:你原有行删除逻辑保留 int i = 0; std::vector<int>::iterator it = boundaryConditions.begin(); while (it != boundaryConditions.end()) { if (*it == 0) { it = boundaryConditions.erase(it); matrix.erase(matrix.begin() + i); } else { it++; i++; } } // 第三步:逐行删除不需要的列,只保留keep_cols里记录的列 for (auto& row : matrix) { std::vector<double> new_row; new_row.reserve(keep_cols.size()); for (int col_idx : keep_cols) { new_row.push_back(row[col_idx]); } row.swap(new_row); } // 输出结果 for (int m = 0; m < matrix.size(); m++) { for (int n = 0; n < matrix[m].size(); n++) { std::cout << std::setw(18) << matrix[m][n]; } std::cout << "\n"; } system("pause>0"); return 0; }
说明
你提供的测试用例中,boundaryConditions为{0,1,1,1,0,0},最终会得到3行3列的矩阵,和预期需求一致。如果后续矩阵规模进一步扩大,也可以将逐行构造新行的逻辑替换为从后往前调用erase删除列的实现,性能差异在100×100规模下可以忽略。
内容的提问来源于stack exchange,提问作者baezacaljo
相关产品推荐
相关产品推荐

