C++ 字符串'的组合向量;s
我有很多字符串向量,每个都包含日期。作为一个简单的例子,向量a 大小为2的可能包含:C++ 字符串'的组合向量;s,c++,string,vector,C++,String,Vector,我有很多字符串向量,每个都包含日期。作为一个简单的例子,向量a 大小为2的可能包含: A[0] = "01-Jul-2010"; A[1] = "03-Jul-2010"; 而大小为3的第二个向量B可能包含: B[0] = "02-Jul-2010"; B[1] = "03-Jul-2010"; B[2] = "04-Jul-2010"; 我想形成一个向量C,它包含a和B中元素的“并集”: C[0] = "01-Jul-2010"; C[1] = "02-Jul-2010"; C[2
A[0] = "01-Jul-2010";
A[1] = "03-Jul-2010";
而大小为3的第二个向量B可能包含:
B[0] = "02-Jul-2010";
B[1] = "03-Jul-2010";
B[2] = "04-Jul-2010";
我想形成一个向量C,它包含a和B中元素的“并集”:
C[0] = "01-Jul-2010";
C[1] = "02-Jul-2010";
C[2] = "03-Jul-2010";
C[3] = "04-Jul-2010";
当组合A和B时,我不希望任何重复的日期,所以C的每个元素都必须是唯一的。有什么内置的/stl(或Boost库)函数可以调用吗
你会这么做吗
谢谢 可以使用集合(但不是多集合)作为(中间)容器,而不是向量。不过,这会删除您可能想要保留的任何订单
您还可以使用std::unique
,std::remove\u if
,或者(假设输入已排序)。在STL中,可以找到两个(按字典顺序)排序序列的并集。假设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));
我想你想要一份工作。这将确保您没有重复项。如果设置不适用,也可以使用std::unique:
std::vector<std::string> A;
std::vector<std::string> B;
std::vector<std::string> C;
A.resize (2u);
B.resize (3u);
A[0] = "01-Jul-2010";
A[1] = "03-Jul-2010";
B[0] = "02-Jul-2010";
B[1] = "03-Jul-2010";
B[2] = "04-Jul-2010";
C.reserve (5u);
std::copy (
A.begin (),
A.end (),
std::back_inserter (C)
);
std::copy (
B.begin (),
B.end (),
std::back_inserter (C)
);
// std::unique requires sorted vector
std::sort (C.begin(), C.end());
C.erase (
std::unique (C.begin(), C.end()),
C.end ()
);
std::向量A;
std::载体B;
std::向量C;
A.调整大小(2u);
B.调整尺寸(3u);
A[0]=“2010年7月1日”;
A[1]=“2010年7月3日”;
B[0]=“2010年7月2日”;
B[1]=“2010年7月3日”;
B[2]=“2010年7月4日”;
C.储备(5u);
复制(
A.begin(),
A.end(),
标准:背向插入器(C)
);
复制(
B.begin(),
B.end(),
标准:背向插入器(C)
);
//std::unique需要排序向量
排序(C.begin(),C.end());
抹去(
std::unique(C.begin(),C.end()),
C.结束()
);
我从你的最后一段中猜到这是一个C++问题,所以我把它标记为这样。它也不与日期相关,所以我删除了那个标签。这是一个C++问题。日期需要按顺序排序。注意,在这种情况下排序是指按词汇排序,而不是按日期排序(因此,“01-OU-2010”将在“02-Jul-2010”之前)。@杰姆斯:如果按日期排序,我们可以提供第六个参数。“第六个参数”,你是指一个比较函数或函子吗?在你的答案中更详细地说明这一点是很好的,因为我认为我们可能会在这一点上失去Wawel100。
std::vector<std::string> A;
std::vector<std::string> B;
std::vector<std::string> C;
A.resize (2u);
B.resize (3u);
A[0] = "01-Jul-2010";
A[1] = "03-Jul-2010";
B[0] = "02-Jul-2010";
B[1] = "03-Jul-2010";
B[2] = "04-Jul-2010";
C.reserve (5u);
std::copy (
A.begin (),
A.end (),
std::back_inserter (C)
);
std::copy (
B.begin (),
B.end (),
std::back_inserter (C)
);
// std::unique requires sorted vector
std::sort (C.begin(), C.end());
C.erase (
std::unique (C.begin(), C.end()),
C.end ()
);