C++ 将现有元素从一个向量复制到另一个向量 [复制]

C++ Copy None Existing Elements from one Vector to another [duplicate]

提问人:Kevin 提问时间:5/9/2022 更新时间:5/9/2022 访问量:67

问:

我有一个这样的类:

struct DataElement {
    std::string key;
    std::string value;
    std::string placeholder;
    // some other data members
}

我将它们存储在 Vector 中。 现在我有一个函数,它接受这些函数并创建 .vectorDataElementvectorDataElement

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 datavector additional_data

我正在考虑使用,但是如何检查当前元素是否已经在目标中?copy_if

C++ 标准 向量

评论

0赞 limserhane 5/9/2022
您可以在 lambda 中捕获。但是,这是 o(N²)。如果这很关键,您可以维护“已复制值”的缓存。std::findadditional_data
1赞 JHBonarius 5/9/2022
实际上:取决于上下文和数据大小。和系统要求。构建地图并最终将其转换回向量甚至可能更快。
2赞 Goswin von Brederlow 5/9/2022
最好使用地图或设置来复制唯一项目。搜索向量将是O(n^2)

答:

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_ifO(N)NO(N^2)std::unordered_mapstd::unordered_map::insertO(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 仅在 中不存在时才插入。这只是两个循环的切换顺序问题。dataadditional_datadata