In place of std :: copy_if

It seems to me that it std::copy_ifwill be very useful for filtering containers:

std::vector<int> vec { 1, 2, 3, 4 };
auto itEnd = std::copy_if(vec.begin(), vec.end(), vec.begin(),
                          [](int i) { return i > 2; });
vec.resize(itEnd - vec.begin());

However, it is std::copy_ifindicated that the input and output ranges may not overlap.

Is there an alternative?

+4
source share
1 answer

copy_if It is primarily intended for copying a range into another range / container. Ie, by its nature, the nature of the algorithm is to copy elements that satisfy a certain condition to another (non-overlapping) range or to a new container.

remove_if , ; , . ; erase, :

std::vector<int> vec { 1, 2, 3, 4 };
vec.erase(std::remove_if(std::begin(vec),
                         std::end(vec),
                         [](int i) { return i <= 2; }),
          std::end(vec));

++, erase-remove.


copy_if, copy , , , copy_backward;

d_first [first, last), std:: copy_backward std:: copy.

+20

Source: https://habr.com/ru/post/1533304/


All Articles