Erasing specific value in a map of vector

Hi there,

Given a map datatype: map<unsigned int, vector<string> > *nodeDataItem
How can i delete specific data elements in the vector mapped to the key?

Usually i will do something like erase(find(vector.begin(), vector.end(), data)) for a pure vector but i am unsure how to do it with a map tied to a key.

Is it possible to do something like (*nodeDataItem)[1].erase("hello")? Thanks!
Last edited on
Is this the way to do it? I have got a segmentation fault though

1
2
3
4
5
6
7
8
9
 map<unsigned int, vector<string> >:: iterator mapIter;
    
    if (!(*nodeDataItem)[finalPeer].empty())
    {

     (*nodeDataItem)[finalPeer].erase(find(mapIter->second.begin(), mapIter->second.end(), data));
    
 }
Last edited on
You're creating an uninitialized iterator, what for?
I want to erase specific elements in a vector which is linked to a key in a map. My idea is to iterate the ->second pair which is the vector itself so that i could find the data i want and erase it from the vector. However i don't think it works for me..

E.g. Key 1 tied to a vector containing string "One" and "Two". I want to be able to find value "Two" from the vector using a given Key value and delete it from the vector. So the final result will be Key 1 with a vector containing string "One".
Do not use operator[] with map unless you are sure that the key exists; the operator adds to the map.
1
2
3
4
5
auto iter { nodeDataItem->find( key ) };
if ( nodeDataItem->end() != iter ) {
  auto & array { iter->second };
  array.erase( std::remove( std::begin(array), std::end(array), value ), std::end(array) );
}

Topic archived. No new replies allowed.