如何从std :: map删除一个键-值对

时间:2019-07-11 13:58:40

标签: c++ stdmap

我正在寻找从std :: map中删除一个key-value元素,并保留存储在此映射中的值。仅仅删除它是不够的,我需要存储在其他地方的键和值。

我的例子是这样的:

std::map<const Class1 *, std::unique_ptr<Class 2>> myMap;

我想从std :: map中提取键和值。仅仅将其移开是不可行的,因为这会使std :: map处于错误状态。

我找到了std :: extract函数,可以将其用于std :: set,但不能用于std :: map。我在网上找不到任何示例,展示了如何从这张地图中提取键和值。

我想做这样的事情:

auto keyAndValue = myMap.extract(myMap.find(instanceOfClass1));

auto key = keyAndValue.someMethod();

auto value = std::move(keyAndValue.someOtherMethod());

我认为我可以使用key()和value(),如一些示例中所述。但这不起作用,我得到一个错误。

error C2039: 'value': is not a member of
'std::_Node_handle<std::_Tree_node<std::pair<const
_Kty,_Ty>,std::_Default_allocator_traits<_Alloc>::void_pointer>,_Alloc,std::_Node_handle_map_base,_Kty,_Ty>'

2 个答案:

答案 0 :(得分:1)

您自己回答了这个问题。

我只想添加一个完整的示例。请参阅:

#include <iostream>
#include <map>
#include <functional>
#include <memory>

struct Class1
{
    void someMethod() const  { std::cout << "Some Method from class 1\n";}
};
struct Class2
{
    Class2(const int i) : test(i) {}
    void someOtherMethod() const  { std::cout << "Some other Method from class 2.  Index: " << test << '\n';}
    int test{0};
};

int main()
{
    Class1 cl1_1{}, cl1_2{}, cl1_3{};

    std::map<const Class1 *, std::unique_ptr<Class2>> myMap;
    // Populate map
    myMap[&cl1_1] = std::make_unique<Class2>(1);
    myMap[&cl1_2] = std::make_unique<Class2>(2);
    myMap[&cl1_3] = std::make_unique<Class2>(3);

    // Extract data    
    auto keyAndValue = myMap.extract(myMap.find(&cl1_1));

    // Get key and value
    auto key = keyAndValue.key();
    auto value = std::move(keyAndValue.mapped());

    // Call methods
    key->someMethod();
    value->someOtherMethod();

    return 0;
}

答案 1 :(得分:0)

马克提出了答案。 对于std :: map,我需要在获取的节点(而不是值)上使用mapted()。 非常感谢!

所以,像这样

auto keyAndValue = myMap.extract(myMap.find(instanceOfClass1));

auto key = keyAndValue.key();

auto value = std::move(keyAndValue.mapped());