问题
无法使用remove_if配合map容器的erase操作按指定条件从map容器删除元素。
C++11 解决方案
可以使用一下函数实现这个需求:
template<typename K, typename V>
void filterMap(map<K, V> & mapObj, bool(*pred)(const K &, const V &))
{
for (auto it = mapObj.begin(), ite = mapObj.end(); it != ite;) {
if (pred(it->first, it->second))
it = mapObj.erase(it);
else
++it;
}
}
示例
代码
#include <map>
#include <iostream>
#include <string>
using namespace std;
template<typename K, typename V>
void filterMap(map<K, V> & mapObj, bool(*pred)(const K &, const V &))
{
for (auto it = mapObj.begin(), ite = mapObj.end(); it != ite;) {
if (pred(it->first, it->second))
it = mapObj.erase(it);
else
++it;
}
}
int main()
{
map<int, string> tmp {
{ 2, "22" },
{ 1, "11" },
{ 4, "44" },
{ 3, "33" },
};
const auto printMap = [& tmp]() {
cout << "Key\tValue" << endl;
for (const auto & it : tmp) {
cout << it.first << "\t" << it.second << endl;
}
};
cout << "Before filter\n";
printMap();
filterMap<int, string>(tmp, [](const int & nKey, const string & sVal) -> bool {
return nKey % 2;
});
cout << "\nAfter filter\n";
printMap();
return 0;
}
运行结果
C++ 20解决方案
可以使用erase_if。