std::how to delete multimap elements

Asked 1 months ago, Updated 1 months ago, 2 views

I understand that std::multimap has the following hash table structure for the purpose of looking at it (it is listed...) (data structure is tree structure).

  • KEY_A
    • DATA_A
    • DATA_B
    • DATA_C
  • KEY_B
    • DATA_D
    • DATA_E
    • DATA_F
  • DATA_A
  • DATA_B
  • DATA_C
  • DATA_D
  • DATA_E
  • DATA_F

What should I do if I want to delete only DATA_A?
This is because it seems that only the key is used to delete elements that can be multi-imap, and the value cannot be deleted.

In the first place, is there a mechanism in multimap that removes values instead of keys and automatically packs empty parts?

Thank you for your cooperation.

Reference URL: http://vivi.dyndns.org/tech/cpp/multimap.html

c++

2022-09-30 11:17

1 Answers

You can delete elements that you have already commented on in erase(iterator position).

// Version to be deleted by specifying a pair
template<class MultiMap>
voiderase(MultiMap&map, typenameMultiMap::value_type const&value){
    map.erase(find(begin(map), end(map), value));
}

// Version to be deleted by specifying data
template<class MultiMap>
voiderase(MultiMap&map,typeNameMultiMap::mapped_type const&mapped){
    map.erase(find_if(begin(map), end(map), & (auto const&value){
        return std::get<1>(value) == mapped;
    }));
}

int main() {
    std::multimap<int,int>m {{0,0},{1,1}};
    erase(m,{0,0});
    erase(m,1);
}

For example, if you have a function like this, you can erase it, but if you can't find a pair or if you find more than one data, the design will change depending on the situation.
(That's why STL only provided basic functions such as deleting with iterator).


2022-09-30 11:17

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.