Skip to content

Commit

Permalink
Documenting algorithm/set_union
Browse files Browse the repository at this point in the history
  • Loading branch information
thamara committed Sep 3, 2019
1 parent 52bcc87 commit 93554b1
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
32 changes: 32 additions & 0 deletions algorithm/set_union.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# set_union

**Description** : Constructs a sorted range beginning in the location passed by result with the set union of the two sorted ranges `[first1, last1)` and `[first2, last2)`.

**Example**:
```cpp
std::vector<int> v1 {3, 1, 5};
std::vector<int> v2 {1, 0};

// the destination needs to fit all merged values, we'll prune the extra elements later
std::vector<int> destination(v1.size() + v2.size());

// set_union requires sorted ranges
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());

// returns iterator to the end of the constructed range
auto it = std::set_union(v1.begin(), v1.end(), // first range
v2.begin(), v2.end(), // second range
destination.begin());

// prune extra values
destination.resize(it - destination.begin());

// destination is now {0, 1, 3, 5}
for (auto value : destination) {
std::cout << value << " ";
}

```
**[See Sample code](snippets/algorithm/set_union.cpp)**
**[Run Code](https://rextester.com/LFXB93097)**
37 changes: 37 additions & 0 deletions snippets/algorithm/set_union.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
Author : Thamara Andrade
Date : Date format 02/09/2019
Time : Time format 02:00
Description : Checks if a range is included in another range.
*/

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

int main()
{
std::vector<int> v1 {3, 1, 5};
std::vector<int> v2 {1, 0};

// the destination needs to fit all merged values, we'll prune the extra elements later
std::vector<int> destination(v1.size() + v2.size());

// set_union requires sorted ranges
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());

// returns iterator to the end of the constructed range
auto it = std::set_union(v1.begin(), v1.end(), // first range
v2.begin(), v2.end(), // second range
destination.begin());

// prune extra values
destination.resize(it - destination.begin());

// destination is now {0, 1, 3, 5}
for (auto value : destination) {
std::cout << value << " ";
}
return 0;
}

0 comments on commit 93554b1

Please sign in to comment.