C ++: remove element from container and return it back

Is there a built-in method that removes the element (i.e., sets the key from the map) and returns the deleted element?

0
source share
2 answers

There is no built-in method for this, however you can save the item by accessing it and then delete it. To erase, you must specify a key. If it is a multi-card, you must delete it using the item.

0
source

Here is a function you can use (C ++ 11):

#include <iostream>
#include <map>

template<typename T>
typename T::mapped_type removeAndReturn(T& mp, const typename T::key_type& val) {
    auto it = mp.find(val);
    auto value = std::move(it->second);
    mp.erase(it);
    return value;
}

int main() {
    std::map<int, int> m;
    m[3] = 4;
    std::cout << "Map is empty: " << std::boolalpha << m.empty() << std::endl;
    std::cout << "Value returned: " << rm_and_return(m, 3) << std::endl;
    std::cout << "Map is empty: " << std::boolalpha << m.empty() << std::endl;
}

Conclusion:

Map is empty: false
Value returned: 4
Map is empty: true
0
source

Source: https://habr.com/ru/post/1569160/


All Articles