I have a 2D std::vector < std::vector <double> >
array consisting of three rows and an unknown number of columns. I would like to delete any column where the value of row 0 > row 1
. Here is my effort:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
inline void printArray (const std::vector< std::vector< T > >& key_array) {
for (int i = 0; i < key_array.size(); i++) {
for (int j = 0; j < key_array[i].size(); j++) {
std::cout << key_array[i][j] << "";
}
std::cout << "
";
}
std::cout << "
";
}
int main()
{
std::vector< std::vector <int> > fog {{1,1,2,1},{2,2,1,2},{3,3,3,3}};
printArray(fog);
for (int i = 0; i < fog[0].size(); ++i) {
for (int j = 0; j < fog.size(); ++j) {
if (fog[0][i] > fog[1][i]) {
fog[j].erase(fog[j].begin() + i);
}
}
}
printArray(fog);
The array is initially:
1 1 2 1
2 2 1 2
3 3 3 3
I would like it to become:
1 1 1
2 2 2
3 3 3
Instead I get:
1 1 1
2 2 1 2
3 3 3 3
I imagine the problem is because the size of the array is changing as elements are deleted, invalidating the loop conditions, and/or iterators are being removed. But with this observation, I have reach my (rather circumscribed) limits.
I would be most grateful for any advice.
question from:
https://stackoverflow.com/questions/65898918/delete-column-in-2d-stdvector-depending-on-comparison-of-2-rows-in-same-column 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…