0

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?

2 Answers2

2

Use erase_if:

const auto count = std::erase_if(possible, [](const auto& item) {
    auto const& [key, value] = item;
    return value == 1;
});
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
  • 1
    Prior to C++20, you will have to use [`map::erase()`](https://en.cppreference.com/w/cpp/container/map/erase) in a loop instead. – Remy Lebeau Jul 02 '22 at 20:44
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;
});
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770