I have a map of vectors in C++. For each vector, I'd like to delete entries that meet a certain condition. If a vector ends up empty, I'd like to delete it from the map. I know deletion can mess up iterators, and doubly iterating makes this even more confusing for me. What's the best way to accomplish this?
Asked
Active
Viewed 88 times
0
-
A little code for context would help here. – tadman Nov 17 '16 at 00:04
-
Generally speaking, its good to show your attempts you've tried..its rarely appropriate to post a question without including some of your code. – Babra Cunningham Nov 17 '16 at 00:24
-
4This is duplicate of http://stackoverflow.com/questions/8234779/how-to-remove-from-a-map-while-iterating-it – Nicholas Smith Nov 17 '16 at 00:27
2 Answers
4
The standard mutating container loop:
for (auto it = m.begin(); it != m.end(); )
{
// work
if (/* need to delete */) // e.g "if (it->second.empty())"
{
it = m.erase(it);
}
else
{
++it;
}
}

Kerrek SB
- 464,522
- 92
- 875
- 1,084
0
Here is a demonstrative program that shows how it can be done
#include <iostream>
#include <map>
#include <vector>
int main()
{
std::map<int, std::vector<int>> m =
{
{ 1, { 1, 2 } },
{ 2, { 2 } },
{ 3, { 3, 4 } },
{ 4, { 4 } }
};
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
for ( auto it = m.begin(); it != m.end(); )
{
it->second.erase( it->second.begin() );
if ( it->second.empty() ) it = m.erase( it );
else ++it;
}
std::cout << std::endl;
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The program output is
1: 1 2
2: 2
3: 3 4
4: 4
1: 2
3: 4

Vlad from Moscow
- 301,070
- 26
- 186
- 335