Skip to content
This repository has been archived by the owner on Nov 8, 2023. It is now read-only.

Explaining the fill_n function #467

Merged
merged 3 commits into from
Feb 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion algorithm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions algorithm/fill_n.md
Original file line number Diff line number Diff line change
@@ -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 <iostream>
#include <vector>
#include <algorithm>

void print_vector(const std::vector<int> &v) {
// iterate through v and print its elements
for(auto &elem:v) {
std::cout << elem << " ";
}
std::cout<<std::endl;
}

int main() {
std::vector<int> 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)**
32 changes: 32 additions & 0 deletions snippets/algorithm/fill_n.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
Author : Klajdi Bodurri
Date : 08/01/2020
Time : 14:00
Description : Show an example of fill_n
*/

#include <iostream>
#include <vector>
#include <algorithm>

void print_vector(const std::vector<int> &v) {
// iterate through v and print its elements
for(auto &elem:v) {
std::cout << elem << " ";
}
std::cout<<std::endl;
}

int main() {
std::vector<int> 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;
}