Reputation: 1395
If I have a map like this:
std::map<char, std::vector<char> > m;
m['A'].push_back('a');
m['A'].push_back('b');
m['A'].push_back('c');
m['B'].push_back('h');
m['B'].push_back('f');
How would I find and delete 'b'? Is this possible?
Upvotes: 1
Views: 443
Reputation: 793109
I'm only reproducing other people's algorithms here, but I find that without a couple of judicious typedefs and temporary reference variables the extra long lines can become significantly less readable.
The original question doesn't fully specify the required behaviour, but it may be appropriate to remove the map entry if the vector is left empty. This could be done as part of the map iterator, or as a pass at the end.
Also might want the remove the first 'b' in the first vector containing a 'b', or all 'b' in every vector, or some combination.
Remove all the 'b' in all the vectors in the map.
typedef std::map<char, std::vector<char> > MapVecChar;
for( MapVecChar::iterator i = m.begin(); i != m.end(); ++i )
{
std::vector<char> &v = i->second;
v.erase( std::remove( v.begin(), v.end(), 'b' ), v.end() );
}
Remove the first 'b' found in a the vector in the map.
typedef std::map<char, std::vector<char> > MapVecChar;
for( MapVecChar::iterator i = m.begin(); i != m.end(); ++i )
{
std::vector<char> &v = i->second;
std::vector<char>::iterator j( std::find( v.begin(), v.end(), 'b' ) );
if( j != v.end() )
{
v.erase( j );
break;
}
}
Remove empty map entries.
for( MapVecChar::iterator i = m.begin(); i != m.end(); )
{
if( i->second.empty() )
m.erase( i++ );
else
++i;
}
Upvotes: 0
Reputation: 994629
Sure, use an iterator:
for (std::map<char, std::vector<char> >::iterator i = m.begin(); i != m.end(); ++i) {
std::vector<char>::iterator j = std::find(i->second.begin(), i->second.end(), 'b');
if (j != i->second.end()) {
i->second.erase(j);
}
}
Upvotes: 6
Reputation: 1616
If you expect there can be multiple 'b's in the vector, I would write this way.
for (std::map<char, std::vector<char> >::iterator i = m.begin(); i != m.end(); ++i) {
i->second.erase(std::remove(i->second.begin(), i->second.end(), 'b'), i->second.end());
}
Upvotes: 1