diff --git a/algorithm/README.md b/algorithm/README.md index 01410e4d..1ff8ed87 100644 --- a/algorithm/README.md +++ b/algorithm/README.md @@ -15,6 +15,7 @@ :heavy_check_mark: [equal](equal.md) :heavy_check_mark: [equal_range](equal_range.md) :heavy_check_mark: [fill](fill.md) +:heavy_check_mark: [fill_n](fill_n.md) :heavy_check_mark: [find](find.md) :heavy_check_mark: [find_first_of](find_first_of.md) :heavy_check_mark: [find_if](find_if.md) @@ -72,7 +73,6 @@ :heavy_check_mark: [upper_bound](upper_bound.md) :x: destroy :x: exclusive_scan -:x: fill_n :x: find_end :x: generate_n :x: inclusive_scan diff --git a/algorithm/fill_n.md b/algorithm/fill_n.md new file mode 100644 index 00000000..c22b8ee7 --- /dev/null +++ b/algorithm/fill_n.md @@ -0,0 +1,35 @@ +# fill_n + +**Description** : Sets a number of elements of a range (i.e, vector) to a value. +The function takes 3 arguments. The iterator of the range, the number of elements +to set starting from the iterator's first element and the new value. + +**Example** : +```cpp + #include + #include + #include + + void print_vector(const std::vector &v) { + // iterate through v and print its elements + for(auto &elem:v) { + std::cout << elem << " "; + } + std::cout< v = {1,1,1,1,1,1,1,1}; + + std::cout << "Before fill_n: "; + print_vector(v); + + // set the first half of v's elements to zero + std::fill_n(v.begin(), v.size()/2, 0); + + std::cout << "After fill_n: "; + print_vector(v); + return 0; + } +``` +**[Run Code](https://rextester.com/CIZQZ21473)** diff --git a/snippets/algorithm/fill_n.cpp b/snippets/algorithm/fill_n.cpp new file mode 100644 index 00000000..4e718fa7 --- /dev/null +++ b/snippets/algorithm/fill_n.cpp @@ -0,0 +1,32 @@ +/* + Author : Klajdi Bodurri + Date : 08/01/2020 + Time : 14:00 + Description : Show an example of fill_n +*/ + +#include +#include +#include + +void print_vector(const std::vector &v) { + // iterate through v and print its elements + for(auto &elem:v) { + std::cout << elem << " "; + } + std::cout< v = {1,1,1,1,1,1,1,1}; + + std::cout << "Before fill_n: "; + print_vector(v); + + // set the first half of v's elements to zero + std::fill_n(v.begin(), v.size()/2, 0); + + std::cout << "After fill_n: "; + print_vector(v); + return 0; +}