Home > Net >  Erase row from 2D vector where element appears?
Erase row from 2D vector where element appears?

Time:04-06

I want to delete evry row in a 2d vector, where an element x appears in row for example : x = 2 vec= {{1,2,4,5},{3,7,9},{2,5,7},{1,6,10}}

result vec= {{3,7,9},{1,6,10}}

I try this

#include <iostream>
#include <vector>
#include <algorithm>

void Delete(std::vector<std::vector<int> > &v, int x)
{
   v.erase(std::remove_if(v.begin(), v.end(), [](const std::vector<int>& v) {int i=0;
  
       return v.size() > 1 && v[i] == x; }), v.end());
}
int main()
{  int x = 1;
   std::vector<std::vector<int>> test = {{1,144,64,62,64,1132},
                                        {1,144,4,62,3,40},
                                        {1,20,64,67,64,1122},
                                        {2,128,1,64}};
    Delete(test, x);
       for (auto& v : test)
    {
       std::cout << "{";
       for (auto& v2 : v)
          std::cout << v2 << " ";
       std::cout << "}\n";
    }
}

CodePudding user response:

One of many errors is the comparing only first elements of the subvectors. You wish

v.erase(std::remove_if(v.begin(), v.end(),
                       [x](const std::vector<int>& v) { return std::find(v.begin(), v.end(), x) != v.end(); }),
        v.end());
  •  Tags:  
  • c
  • Related