c++ - 为什么 STL map 不起作用?

标签 c++ dictionary stl hashmap

我正在用 C++ 在 LeetCode 上写一小段代码。问题是:

给定一个链表,每个节点包含一个额外的随机指针,该指针可以指向列表中的任何节点或 null。 返回列表的深层拷贝。

我的方法是获取一个 HashMap ,并用节点指针作为键和随机指针作为值来填充它。然后进行两次迭代,第一次复制仅包含下一个指针的 LinkedList,第二次复制随机指针。

我编写了以下代码片段,但它抛出了一个奇怪的编译错误

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        std::map<RandomListNode*, RandomListNode*> m;
        RandomListNode *curr = head;
        while(curr!=NULL){
            m.insert(curr, curr->random);
            curr = curr->next;
        }

        curr = head;
        RandomListNode *newHead = NULL;
        RandomListNode *curr2 = NULL;
        while(curr!=NULL){
            if(newHead == NULL){
                newHead = new RandomListNode(curr->label);
                newHead->next = NULL;
                curr2 = newHead;
            }
            else{
                RandomListNode *tempNode = new RandomListNode(curr->label);
                tempNode->next = NULL;
                curr2->next = tempNode;
                curr2 = curr2->next;
            }
            curr = curr->next;
        }
        curr2 = newHead;
        while(curr2!=NULL){

            std::map<RandomListNode*, RandomListNode*>::const_iterator pos = m.find(curr2);
            curr2->random = pos->second;
            curr2 = curr2->next;
        }
        return newHead;

    }
};

并且代码抛出以下错误:

required from 'void std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(_II, _II) [with _InputIterator = RandomListNode*; _Key = RandomListNode*; _Val = std::pair<RandomListNode* const, RandomListNode*>; _KeyOfValue = std::_Select1st<std::pair<RandomListNode* const, RandomListNode*> >; _Compare = std::less<RandomListNode*>; _Alloc = std::allocator<std::pair<RandomListNode* const, RandomListNode*> >]'

有人可以帮我确定我哪里出错了吗? 谢谢!

最佳答案

罪魁祸首是这条指令:

m.insert(curr, curr->random);

std::map::insert takes a single argument ,这是一个 std::pair。您应该创建一对,然后将其插入:

m.insert(std::make_pair(curr, curr->random));

关于c++ - 为什么 STL map 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42484038/

相关文章:

python - 迭代 Python 字典时修改它

c++ - std::vector 元素中的常量引用

c++ - 如何将 vector<char*> 转换为 vector<string>/string

c++ - 无法编译 SDL 发布版本

没有键时的Python字典默认值

python - 迭代具有不同元素的列表

c++ - STL maps中的key是如何升序排列的?

c++ - C++ 中奇怪的 null ref

c++ - union int bits to float bits 有时解释错误

c++ - 使用同名的类和枚举?