【问题标题】:How to remove the a vector element from unordered_map如何从 unordered_map 中删除向量元素
【发布时间】:2021-02-15 10:38:41
【问题描述】:

如何从 unordered_map 中删除矢量元素

std::unordered_map<std::string stdstrID, std::vector<std::string>> controlTags;

我将有多个值作为给定键名,并希望从向量列表中删除键名的给定值。

void Sum_TagControl::Remove_Tag(std::string stdstrControlID , std::string stdstrName) {
    
    for (auto tagData : controlTags[stdstrControlID]) {
        if (tagData == stdstrName) {
            // remove this text element from the  vector list.
        }
    
    }   
}

【问题讨论】:

  • 如果键 stdstrControlID 中尚不存在空向量,您是否打算在 controlTags 中自动创建一个空向量?因为这就是这段代码要做的事情。只是好奇。
  • @WhozCraig 我确实创建了它。
  • if (controlTags.find(stdstrControlID) == controlTags.end()) { controlTags[stdstrControlID] = std::vector<:string>(); // 使用空向量初始化键 }
  • 密钥是std::strings ? std::unordered_map&lt;std::string stdstrID, ... 看起来不对。请发帖minimal reproducible example
  • 除了stdstr 看起来像一些糟糕的匈牙利符号。

标签: c++ c++11 c++14


【解决方案1】:

根据示例,您似乎不想从地图中删除元素,而是希望从恰好位于地图中的向量中删除元素。这与从任何向量中删除元素的方式相同,无论它在哪里。典型的方式是remove-erase idiom。

我假设您的意图不是让Remove_Tag 添加一个空向量,以防stdstrControlID 尚不存在于地图中。我已在以下示例中解决了这个问题:

auto it = controlTags.find(stdstrControlID);
if (it != controlTags.end()) {
    it->erase(std::remove(it->begin(), it->end(), stdstrName));
}

请注意,矢量擦除具有线性复杂性。如果这是一个经常执行的操作并且向量有很多元素,那么使用无序(多)集合而不是向量会更有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    相关资源
    最近更新 更多