C++将无现有元素从一个向量复制到另一个矢量
我有这样的课程:
struct DataElement {
std::string key;
std::string value;
std::string placeholder;
// some other data members
}
我将它们存储在矢量中。 现在,我有了一个功能,该函数采用了这些dataElement
的vector
,并且还创建了vector
dataElement
的。
std::vector<DataElement> doAction(std::vector<DataElement>& data) {
auto additional_data = create_additional_data() //returns std::vector<DataElement>
//merge data and additional_data
return additional_data
}
现在,我想将所有元素从vector数据
复制到vector afred_data
(如果尚不存在的密钥)。
我正在考虑使用copy_if
,但是如何检查当前元素是否已经在目标中?
I have a class like this:
struct DataElement {
std::string key;
std::string value;
std::string placeholder;
// some other data members
}
I store them inside a Vector.
Now i have a function which takes a vector
of these DataElement
and also creates a vector
of the DataElement
.
std::vector<DataElement> doAction(std::vector<DataElement>& data) {
auto additional_data = create_additional_data() //returns std::vector<DataElement>
//merge data and additional_data
return additional_data
}
Now i want to copy all the Elements from the vector data
into the vector additional_data
if there key is not already there.
I was thinking of using copy_if
but how do i check if the current element is already in the Destination?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我更喜欢检查当前元素是否已经在目的地中使用附加
unordered_map
I prefer to check if the current element is already in the Destination with an additional
unordered_map
您可以使用
std :: find_if
检查给定键的元素是否已经在向量中。但是,
std :: find_if
是o(n)
,当您为n
元素进行操作时,您最终会带有o( n^2)
。考虑使用std :: unordered_map
而不是向量。std :: unordered_map :: insert
是o(1)
插入单个元素。如果您不能切换到
std :: Unordered_map
,则在构建向量时仍然可以使用一个:当两个向量都包含一个用于给定键时,我不确定您要保留哪个向量。上面的代码使用
数据
中的一个代码,仅在data
中不存在from_data
中的代码。这只是两个循环切换顺序的问题。You could use
std::find_if
to check if an element with given key is already in the vector.However,
std::find_if
isO(N)
and when you do it forN
elements you end up with aO(N^2)
. Consider to usestd::unordered_map
instead of vectors.std::unordered_map::insert
isO(1)
on average for inserting a single element.If you cannot switch to
std::unordered_map
, you can still use one while building the vector:I wasnt sure from which vector you want to keep the element when both vectors contain one for a given key. The above code uses the one from
data
and the one fromadditional_data
is only inserted when it wasnt present indata
. Its just a matter of switching order of the two loops.