diff --git a/algorithm/copy_if.md b/algorithm/copy_if.md new file mode 100644 index 00000000..dbf352b0 --- /dev/null +++ b/algorithm/copy_if.md @@ -0,0 +1,23 @@ +# copy_if + +**Description** : Copies the elements in the range, defined by `[first, last)`, to another range beginning at passed argument, if the value satisfy specific criteria. + +**Example**: +```cpp + auto isOdd = [](int i) { + return ((i%2) == 1); + }; + + std::vector origin {1, 2, 3}; + std::vector destination; + + // Will copy from origin [begin, end), to destination + std::copy_if(origin.begin(), origin.end(), std::back_inserter(destination), isOdd); + + // destination is now {1, 3} + for (auto value : destination) { + std::cout << value << " "; + } +``` +**[See Sample code](snippets/vector/copy_if.cpp)** +**[Run Code](https://rextester.com/OMC23438)** \ No newline at end of file diff --git a/snippets/algorithm/copy_if.cpp b/snippets/algorithm/copy_if.cpp new file mode 100644 index 00000000..e2173eb5 --- /dev/null +++ b/snippets/algorithm/copy_if.cpp @@ -0,0 +1,28 @@ + /* + Author : Thamara Andrade + Date : Date format 02/09/2019 + Time : Time format 02:00 + Description : Copies the elements in one range to another range if it matches a condition. +*/ + +#include +#include +#include + +int main() +{ + auto isOdd = [](int i) { + return ((i%2) == 1); + }; + + std::vector origin {1, 2, 3}; + std::vector destination; + + // Will copy from origin [begin, end), to destination + std::copy_if(origin.begin(), origin.end(), std::back_inserter(destination), isOdd); + + // destination is now {1, 3} + for (auto value : destination) { + std::cout << value << " "; + } +} \ No newline at end of file