2

I have some trouble with removing a empty vector in a vector using the remove-erase idiom like Erasing elements from a vector. How can I apply this on:

vector<vector<Point> > contours; // want to remove contours.at(i).empty()
contours.erase(remove(contours.begin(), contours.end(), ??? ),contours.end());
Community
  • 1
  • 1
aagaard
  • 1,596
  • 2
  • 14
  • 28

3 Answers3

10

Have you tried:

contours.erase(remove(contours.begin(), contours.end(), vector<Point>()), contours.end());
moswald
  • 11,491
  • 7
  • 52
  • 78
5

Use remove_if that takes a predicate.

contours.erase(
    std::remove_if(
         contours.begin(), contours.end(),
         [](const vector<Point>& v) { return v.empty(); }
         // or a functor/plain function/Boost.Lambda expression
    ), contours.end()
);
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • It's works! Nice suggestion, I actually looked at during it with lambda expressions, so thank you for your suggestion. – aagaard Dec 13 '11 at 15:46
  • Although everybody likes lambdas, I find `std::mem_fn(&std::vector::empty)` even more concise and clear. – Christian Rau Jan 14 '13 at 12:11
2

use remove_if.

C++11

contours.erase(
    std::remove_if(contours.begin(), contours.end(), 
        [&](const Vector<Point>& vp){
            return vp.empty();
        }),
        contours.end());

C++03

struct is_empty
{
    bool operator()(const Vector<Point>& vp) constt;
    {
        return vp.empty();
    }
}


contours.erase(
         std::remove_if(contours.begin(), contours.end(), 
         is_empty,
         contours.end());
111111
  • 15,686
  • 6
  • 47
  • 62
  • 1
    You don't need a custom functor in C++03, a simple `std::mem_fun_ref(&std::vector::empty)` should suffice. – Christian Rau Dec 14 '12 at 09:05
  • The same holds for C++11, just with `std::mem_fn`, where it's also more concise and conceptually cleaner than a lambda, but Ok, that is maybe rather a matter of taste. But for C++03, not using its scarce functional facilities when they finally make perfect sense is a little bit of a crime ;) – Christian Rau Dec 14 '12 at 09:11
  • By the way, it should be `const` istead of `constt` and `is_empty()` instead of just `is_empty` inside the function call. – Christian Rau Dec 14 '12 at 09:12