如何从 unordered_map 中删除向量元素
How to remove the a vector element from unordered_map
如何从 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.
}
}
}
根据示例,您似乎不想从地图中删除元素,而是想从恰好位于地图中的向量中删除元素。这与从任何向量中删除元素的方式相同,无论它在哪里。典型的方式是remove-erase idiom.
我假设您的意图不是 Remove_Tag
添加空向量以防 stdstrControlID
不存在于地图中。我在以下示例中修复了此问题:
auto it = controlTags.find(stdstrControlID);
if (it != controlTags.end()) {
it->erase(std::remove(it->begin(), it->end(), stdstrName));
}
请注意,矢量擦除具有线性复杂度。如果这是一个经常执行的操作并且向量有很多元素,那么使用无序(多)集而不是向量会更有效。
如何从 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.
}
}
}
根据示例,您似乎不想从地图中删除元素,而是想从恰好位于地图中的向量中删除元素。这与从任何向量中删除元素的方式相同,无论它在哪里。典型的方式是remove-erase idiom.
我假设您的意图不是 Remove_Tag
添加空向量以防 stdstrControlID
不存在于地图中。我在以下示例中修复了此问题:
auto it = controlTags.find(stdstrControlID);
if (it != controlTags.end()) {
it->erase(std::remove(it->begin(), it->end(), stdstrName));
}
请注意,矢量擦除具有线性复杂度。如果这是一个经常执行的操作并且向量有很多元素,那么使用无序(多)集而不是向量会更有效。