繁体   English   中英

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

[英]Howto remove one key - value pair from std::map

我想从std :: map中删除一个键-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>'

您自己回答了这个问题。

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

#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;
}

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

所以像这样

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

auto key = keyAndValue.key();

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

暂无
暂无

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

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