C++如何按值从std ::映射中删除项目?

发布于 2025-02-12 10:00:14 字数 212 浏览 0 评论 0原文

我的地图:

std::map<std::array<byte, 16>, int> possible; // key is a byte array, value is a frequency of occurrence

我已经填写了地图。现在,我需要删除一次发生的阵列。有必要从地图上删除这样的对,其值等于一个。怎么做?

My map:

std::map<std::array<byte, 16>, int> possible; // key is a byte array, value is a frequency of occurrence

I already filled the map. Now I need to remove the arrays that occurred once. It is necessary to remove from the map such pairs, the value of which is equal to one. How to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

分開簡單 2025-02-19 10:00:16

使用 erase_if

const auto count = std::erase_if(possible, [](const auto& item) {
    auto const& [key, value] = item;
    return value == 1;
});

Use erase_if:

const auto count = std::erase_if(possible, [](const auto& item) {
    auto const& [key, value] = item;
    return value == 1;
});
话少情深 2025-02-19 10:00:16

std :: Map并非旨在按值逐值找到元素。因此,要按照您的要求,您将必须手动循环循环MAP调用 map :: erase() 在所需的项目上,例如:

auto iter = possible.begin();
while (iter != possible.end()) {
  if (iter->second == 1) {
    iter = possible.erase(iter);
  } else {
    ++iter;
  }
}

在C ++ 20及以后,您可以使用 std :: map std :: erase_if(),例如:

std::erase_if(possible, [](const auto& item) {
    return item.second == 1;
});

std::map isn't designed to find elements by value, only by key. So, to do what you are asking for, you will have to manually loop through the map calling map::erase() on the desired items, eg:

auto iter = possible.begin();
while (iter != possible.end()) {
  if (iter->second == 1) {
    iter = possible.erase(iter);
  } else {
    ++iter;
  }
}

In C++20 and later, you can use the std::map overload of std::erase_if() instead, eg:

std::erase_if(possible, [](const auto& item) {
    return item.second == 1;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文