c++ - 删除 std::map 中的特定元素

标签 c++ algorithm stl map containers

我想删除我的 std::map 中的一些元素。
我编写了删除 + remove_if 技术,我总是使用其他序列容器。
但它不是用 map 编译的。为什么?
我该如何做这份工作?

std::map<int, int> m;

bool foo(const std::pair<int, int>& p)
{
    return p.second > 15;
}

int _tmain(int argc, _TCHAR* argv[])
{
    m.insert(make_pair(0, 0));
    m.insert(make_pair(1, 10));
    m.insert(make_pair(2, 20));
    m.insert(make_pair(3, 30));

    m.erase(
        remove_if(m.begin(), m.end(), foo),
        m.end()); // compile error

    return 0;
}

最佳答案

为 map 写成这样,因为 remove_if 不适用于 map 迭代器(它只是将有问题的元素放在末尾,而 map 迭代器不允许这样做):

template <typename Map, typename F>
void map_erase_if(Map& m, F pred)
{
    typename Map::iterator i = m.begin();
    while ((i = std::find_if(i, m.end(), pred)) != m.end())
        m.erase(i++);
}

或者如果你喜欢单行:

template <typename Map, typename F>
void map_erase_if(Map& m, F pred)
{
    for (typename Map::iterator i = m.begin();
         (i = std::find_if(i, m.end(), pred)) != m.end();
         m.erase(i++));
}

关于c++ - 删除 std::map 中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7007802/

相关文章:

c++ - 使用 int 进行枚举类初始化

mysql - 基于投票从 1 到 5 的人气排名算法

algorithm - 跨多个字写入多个位的高效算法

c++ - 如何在 STL map(set) 中查找范围内的所有元素

c++ - 为什么 C++11 或 C++14 中没有位置迭代器?

c++ - CMP 是如何在 C++ 中定义的?用 < 或用 <=?

c++ - dup2( ) 导致子进程提前终止

c++ - 调用 gcc _without_ -pthread 有什么好处?

c++ - 在 C/C++ 中获得正模的最快方法

c++ - 二维矩形的 boolean 运算