删除std :: map中的特定元素 [英] Erase specific elements in std::map
本文介绍了删除std :: map中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要删除我的std :: map中的一些元素。
我写了erase + remove_if技术,我总是使用其他序列容器。
但它不是编译与地图。为什么?
我该如何做这项工作?
I want to erase some elements in my std::map.
I wrote erase + remove_if technique which I always do with other sequence containers.
But it wasn't compile with map. Why?
And How can I do this job?
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;
}
推荐答案
,因为 remove_if
将不能用于 map
迭代器(它只是在冒犯的元素, $ c> map 迭代器不允许这样):
Write it like this for map, since remove_if
won't work for map
iterators (it merely puts offending elements at the end, and map
iterators don't allow for this):
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++);
}
或者如果您喜欢one-liners:
or if you like one-liners:
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++));
}
这篇关于删除std :: map中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文