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;
}
Using erase() : erase() is used to erase the pair in map mentioned in argument, either its position, its value or a range of number. erase(key) : Erases the key-value pair using key mentioned in its argument.
map::clear() function is an inbuilt function in C++ STL, which is defined in header file. clear() is used to remove all the content from the associated map container. This function removes all the values and makes the size of the container as 0.
clear() The clear() method removes all elements from a Map object.
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++);
}
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++));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With