4 ms·
You can simplify that code a bit, since the contents of a `std::vector` are guaranteed to be contiguous in C++03 and later, and taking a pointer offset is there
by smitherfield 10y ago
You can simplify that code a bit, since the contents of a `std::vector` are guaranteed to be contiguous in C++03 and later, and taking a pointer offset is therefore well-defined and correct.
const auto last{ std::copy_if(vec.cbegin(), vec.cend(), vec.begin(),
[](const auto x) { return x > 2; }) };
vec.resize(last - vec.cbegin());
Edit: As someone mentioned below, C++ also provides `std::remove_if()`, for a more exact analogue to Ruby `Enumerable#reject`. http://en.cppreference.com/w/cpp/algorithm/remove http://en.cppreference.com/w/cpp/algorithm/remove
const auto last{ std::remove_if(vec.cbegin(), vec.cend(), vec.begin(),
[](const auto x) { return x <= 2; }) };
vec.resize(last - vec.cbegin());
- catnaroek 10y ago`std::remove_if` only takes two iterator arguments, and it's too ad hoc in exactly the same way Ruby's `reject!` is too ad hoc: it's the result of specializing `std::copy_if` to the case when the zeroth and second iterator arguments agree.
- smitherfield 10y agoMy mistake; I read about it (http://en.cppreference.com/w/cpp/algorithm/remove http://en.cppreference.com/w/cpp/algorithm/remove) too fast and thought it was the simple inverse of copy. I wasn't aware of it before this thread. In the unlikely event some future reader is copy-pasting these snippets, here's the corrected version: const auto last{ std::remove_if(vec.begin(), vec.end(), [](const auto x) { return x <= 2; }) }; vec.resize(last - vec.cbegin());
- marvy 10y agoremove_if is a convenience method; for full generality you can use remove_copy_if. I don't see how any of this allows you to achieve your idea of two independent containers backed by the same storage and thereby eliminate the extra step of calling resize.