elegant way to remove all elements of a vector that are contained in another vector?

后端 未结 5 777
Happy的楠姐
Happy的楠姐 2021-02-14 00:08

While looking over some code I found loopy and algorithmically slow implementation of std::set_difference :

 for(int i = 0; i < a.size(); i++)
 {
  iter = std         


        
5条回答
  •  深忆病人
    2021-02-14 00:40

    The current code is quite clear, in that it should be obvious to any programmer what's going on.

    The current performance is O(a.size() * b.size()), which may be pretty bad depending upon the actual sizes.

    A more concise and STL-like way to describe it is to use remove_if with a predicate that tells you if a value in in a.

    b.erase(std::remove_if(b.begin(), b.end(), [](const auto&x) {
      return std::find(a.begin(), a.end(), x) != a.end();
    }), b.end());
    

    (Not tested, so I might have made a syntax error.) I used a lambda, but you can create a functor if you're not using a C++11 compiler.

    Note that the original code removes just one instance of a value in b that's also in a. My solution will remove all instances of such a value from b.

    Note that the find operation happens again and again, so it's probably better to do that on the smaller vector for better locality of reference.

提交回复
热议问题