我有许多字符串向量,每个字符串包含日期.作为一个简单的例子,大小为2的向量A可能包含:
A[0] = "01-Jul-2010";
A[1] = "03-Jul-2010";
Run Code Online (Sandbox Code Playgroud)
而第3个大小为3的向量B可能包含:
B[0] = "02-Jul-2010";
B[1] = "03-Jul-2010";
B[2] = "04-Jul-2010";
Run Code Online (Sandbox Code Playgroud)
我想形成一个向量C,其中包含A和B中元素的"联合":
C[0] = "01-Jul-2010";
C[1] = "02-Jul-2010";
C[2] = "03-Jul-2010";
C[3] = "04-Jul-2010";
Run Code Online (Sandbox Code Playgroud)
当组合A和BI时,不需要任何重复日期,因此C的每个元素必须是唯一的.是否有我可以调用的内置/ stl(或Boost库)函数可以执行此操作?
谢谢!
在STL中有一个 set_union 函数可以找到两个(按字典顺序排序)排序的序列的并集.假设A和B已经排序,
#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));
Run Code Online (Sandbox Code Playgroud)
如果A和B按日期排序,则需要提供日期比较功能/仿函数,例如
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);
Run Code Online (Sandbox Code Playgroud)