给定一个二维数组,把零元素删除,如果一个行全是零元素,则把该行删除。
行从尾到头遍历(为了删除行的时候方便确定iter的位置),行元素从头到尾遍历
如果行元素被删完,则该行的vector size为0,根据该条件删除行。
vector<vector<int>> test;
test.resize(5);
for (int i = 0; i < test.size(); i++) test[i].resize(4);
test[0][1] = 1;
test[2][2] = 1;
test[2][3] = 1;
cout << "begin size:" << test.size() << endl;
for (int i = 0; i < test.size(); i++) {
for (int j = 0; j < test[i].size(); j++) {
cout << test[i][j] << " ";
}
cout << endl;
}
vector<vector<int>>::iterator iter;
for (int i = test.size() - 1; i >= 0; i--) {
for (vector<int>::iterator it = test[i].begin(); it != test[i].end();) {
if (*it == 0) {
it = test[i].erase(it);
}
else it++;
}
if (!test[i].size()) {
iter = test.begin() + i;
test.erase(iter);
}
}
cout << "after size:" << test.size() << endl;
for (int i = 0; i < test.size(); i++) {
for (int j = 0; j < test[i].size(); j++) {
cout << test[i][j] << " ";
}
cout << endl;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)