How to use lambda to erase empty vector cells?

2020-05-09 10:18发布

问题:

I have a vector:

std::vector<Edge> edges(num);

which contain empty cells at the end, which I would like to remove using lambda but when I did:

edges.erase(std::remove_if(edges.begin(), edges.end(), 
                       std::mem_fn(&std::Edge::empty), edges.end() );

I got this error:

error C2664: 'bool main::<lambda_6f33349b59d49f69703a5fa6a8c5995a>::operator ()(const std::vector<_Ty> &) const' : cannot convert parameter 1 from 'Edge' to 'const std::vector<_Ty> &'

What do I do now?

回答1:

How to use lambda to erase empty vector cells?

You just need to provide a simple lambda that returns true if an Edge is empty:

edges.erase(std::remove_if(edges.begin(), 
                           edges.end(), 
                           [](const Edge& e){return e.empty();}), 
            edges.end() );

This assumes Edge has a suitable member function empty():

class Edge
{
 public:

  bool empty() const { .... }

  // as before
};


标签: c++ c++11 vector