本文内容来自C++Plus,本文只是本人的总结和翻译而已。本人只是C++的搬运工。
原文传送门:http://www.cplusplus.com/reference/algorithm/copy_if/
copy_if算法:copy区间范围内的某一个值。
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) {
*result = *first;
++result;
}
++first;
}
return result;
}
copy_if算法,就是在copy算法的基础上可以多加上一个选择条件。符合pred方法里面条件的就留下来,其他的都不要。然后给copy到一个指定的区间范围内。
// copy_if example
#include <iostream> // std::cout
#include <algorithm> // std::copy_if, std::distance
#include <vector> // std::vector
int main () {
std::vector<int> foo = {25,15,5,-5,-15};
std::vector<int> bar (foo.size());
// copy only positive numbers:
auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
bar.resize(std::distance(bar.begin(),it)); // shrink container to new size
std::cout << "bar contains:";
for (int& x: bar) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
注意:copy_if算法很重要,比如需要查找某个数据出来修改,就直接copy_if出来到一个容器中,然后改了在写回文件中就OK了。很好用。。。。。