c++ map.emplace() 不起作用,但operator[] 可以

问题描述 投票:0回答:1
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <unordered_map>
#include <unordered_set>

using namespace std;

// 双向链表
struct ListNode {
    int times;
    unordered_set<string> bucket;
    ListNode *prev;
    ListNode *next;

    ListNode() {
        prev = nullptr;
        next = nullptr;
    }

    ListNode(int times, string key) : ListNode() {
        this->times = times;
        bucket.emplace(key);
    }
};

int main() {
    unordered_map<string, ListNode *> map;
    ListNode *node = new ListNode();
    map.emplace("haha", node);
//    map["haha"] = node;
    ListNode *node2 = new ListNode(1, "x");
    map.emplace("haha", node2);
//    map["haha"] = node2;
}
  • 调试图像:

在此输入图片描述

  • 为什么关键字haha对应的值没有变化? 它应该是 0xec1e20 而不是 0xec1c90。
  • 当我使用操作符[]时,我可以成功更改对应的值哈哈
c++ emplace
1个回答
0
投票

std::map::emplace
添加具有给定键的新元素 - 但前提是该键尚不存在:

将一个新元素插入到使用给定参数就地构造的容器中,如果容器中没有带有该键的元素。

(重点是我的)

© www.soinside.com 2019 - 2024. All rights reserved.