简体   繁体   中英

Why is STL Map not working?

I am writing a small code snippet at LeetCode in C++. The problem is:

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list.

My approach is to take a hashmap and fill it with node pointers as keys and random pointers as values. Then do two iterations, one to copy the LinkedList with only next pointers and the second one to copy the random pointers.

I have written the following code snippet but its throwing a weird compilation error .

/**
 * 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;

    }
};

And the code throws the following error:

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*> >]'

Can someone please help me in identifying where I am going wrong? thanks!

The culprit is this instruction:

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

std::map::insert takes a single argument , which is an std::pair . You should create a pair, then insert it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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