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
source
share