Filter out elements from std::vector I have ended up with the following code in order to filter out some bad elements from a std::vector:

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;

typedef struct mystruct {
    int id;
    std::string name;
};

int main()
{        
    std::vector&lt;mystruct&gt; all_items = {{151, "test1"}, {154, "test4"}, {152, "test2"}, {151, "test1"}, {151, "test1"}, {153, "test3"}};
    std::vector&lt;int&gt; bad_ids = {151, 152};
    std::vector&lt;mystruct&gt; filter_items;

    for (const auto&amp; item : all_items) {
        if ( std::find(bad_ids.begin(), bad_ids.end(), item.id) != bad_ids.end() ) {
            std::cout &lt;&lt; "id: " &lt;&lt; item.id &lt;&lt; " is bad" &lt;&lt; std::endl;
        } else {
            std::cout &lt;&lt; "id: " &lt;&lt; item.id &lt;&lt; " is good item" &lt;&lt; std::endl;
            filter_items.emplace_back(item);
        }
    }

    for (auto f : filter_items) {
        std::cout &lt;&lt; "Good item: " &lt;&lt; f.id &lt;&lt; std::endl;
    }
}


Is there any more efficient way? Can the std::remove_copy_if or Boost be used here and how?
You're essentially copying copy_if with some additional debug messages. One can rewrite your code with

std::copy_if(all_items.begin(), all_items.end(), std::back_inserter(filter_items),
             [&amp;bad_ids](const mystruct&amp; item)
{
     return std::find(bad_ids.begin(), bad_ids.end(), item.id) == bad_ids.end();
});


But that's not necessarily more efficient, because copy_if and remove_copy_if are usually implemented as

for(; first != last; ++first) {
    if(predicate(*first)){     // copy if; remove_copy_if would negate
        *result = *first;
        result++;
    }
}


A more efficient way would be a faster predicate, e.g. instead of find(bad_ids…) you could use

for(const auto &amp; item : all_items) {
    if(item.id &lt; 151 || 152 &lt; item.id) {
        filtered_items.push_back(item);
    }
}


But that's not as flexible anymore. That being said, we're talking about a small code snippet. As always, you should measure the time your code needs. And in this case, the output by cout will most likely take the most time.

For now, use the variant that you understand best. Your code is fine, there's not much one can improve at that point without resorting to personal preference because it's too short.

By the way, I would call filter_items filtered_items instead, since it doesn't actually filter items. It is a std::vector of items that have been filtered.