提问人:Kevin 提问时间:5/9/2022 更新时间:5/9/2022 访问量:67
C++ 将现有元素从一个向量复制到另一个向量 [复制]
C++ Copy None Existing Elements from one Vector to another [duplicate]
问:
我有一个这样的类:
struct DataElement {
std::string key;
std::string value;
std::string placeholder;
// some other data members
}
我将它们存储在 Vector 中。
现在我有一个函数,它接受这些函数并创建 .vector
DataElement
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
}
现在我想将所有元素从 复制到 if there 键中。vector data
vector additional_data
我正在考虑使用,但是如何检查当前元素是否已经在目标中?copy_if
答:
0赞
ramsay
5/9/2022
#1
我更喜欢检查当前元素是否已经在目标中,并附加一个unordered_map
std::vector<DataElement> doAction(std::vector<DataElement>& data) {
std::vector<DataElement> result = data;
std::unordered_map<std::string, DataElement> merged;
for(const auto& e: data){
merged[e.key] = e;
}
auto additional_data = create_additional_data() //returns std::vector<DataElement>
// Time complexity: O(N)
for(const auto &e: additional_data){
// it's O(1) complexity
if(merged.find(e.key) == merged.end()){
result.push_back(e);
merged[e.key] = e;
}
}
//merge data and additional_data
return result;
}
0赞
463035818_is_not_an_ai
5/9/2022
#2
您可以使用它来检查具有给定键的元素是否已经在向量中。std::find_if
但是,当你对元素执行此操作时,你最终会得到一个.考虑使用矢量代替矢量。 平均而言,插入单个元素。std::find_if
O(N)
N
O(N^2)
std::unordered_map
std::unordered_map::insert
O(1)
如果无法切换到 ,您仍然可以在构建向量时使用一个:std::unordered_map
#include <string>
#include <vector>
#include <unordered_map>
struct DataElement {
std::string key;
std::string value;
std::string placeholder;
// some other data members
};
std::vector<DataElement> create_additional_data() { return {}; }
std::vector<DataElement> doAction(std::vector<DataElement>& data) {
auto additional_data = create_additional_data();
std::vector<DataElement> result;
std::unordered_map<std::string,DataElement> temp;
for (const auto& e : data) { temp.insert({e.key,e}); }
//merge data and additional_data
// element is not inserted when key is already present !
for (const auto& e : additional_data) { temp.insert({e.key,e});}
for (const auto& e : temp) { result.push_back(e.second); }
return result;
}
我不确定当两个向量都包含给定键的一个向量时,您想从哪个向量保留该元素。上面的代码使用 from 和 from 的 one 仅在 中不存在时才插入。这只是两个循环的切换顺序问题。data
additional_data
data
评论
std::find
additional_data
O(n^2)