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

后端 未结 5 856
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:30

    One solution that comes to mind is combining remove_if and binary_search. It's effectively the same as your manual looping solution but might be a bit more "elegant" as it uses more STL features.

    sort(begin(b), end(b));
    auto iter = remove_if(begin(a), end(a), 
                          [](auto x) { 
                              return binary_search(begin(b), end(b), x); 
                          });
    // Now [begin(a), iter) defines a new range, and you can erase them however
    // you see fit, based on the type of a.
    

提交回复
热议问题