简体   繁体   English

c ++:从容器中删除元素并将其取回

[英]c++: Remove element from container and get it back

是否有一个内置方法可以删除和元素(即从给定键的映射中)并返回被删除的元素?

There is no built-in method to do this, you can however store the element by accessing it and then erase it. 没有内置方法可以执行此操作,但是您可以通过访问元素然后将其擦除来存储元素。 Erasing requires you to specify key.If it's a multi-map you should erase with position. 擦除需要您指定关键点。如果是多地图,则应删除其位置。

Here is a function you can use (C++11): 这是您可以使用的功能(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;
}

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM