I have a number of vectors of strings each containing dates. As a simple example vector A of size 2 might contain:
A[0] = "01-Jul-2010";
A[1] = "03-Jul-2010";
while a second vector B of size 3 might contain:
B[0] = "02-Jul-2010";
B[1] = "03-Jul-2010";
B[2] = "04-Jul-2010";
I'd like to form a vector C which contains the 'union' of the element in A and B:
C[0] = "01-Jul-2010";
C[1] = "02-Jul-2010";
C[2] = "03-Jul-2010";
C[3] = "04-Jul-2010";
When combining A and B I don't want any repeated dates so each element of C must be unique. Is there any in-built/stl (or Boost library) function I can call that will do this?
Thanks!
There is a set_union function in STL to find the union of two (lexicographically) sorted sequences. Assuming A and B are already sorted,
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
...
std::vector<std::string> C;
std::set_union(A.begin(), A.end(), B.begin(), B.end(), std::back_inserter(C));
If A and B are sorted by date, you need to supply that date-comparing function / functor, e.g.
bool is_earlier(const std::string& first_date, const std::string& second_date) {
// return whether first_date is earlier than second_date.
}
...
std::set_union(A.begin(), A.end(), B.begin(), B.end(),
std::back_inserter(C), is_earlier);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With