I somehow not sure what is wrong with call to insert for the object "history" where history is of type map. I have checked that there should be an insert function for a map object where the insert function would take in a pair as an argument. However I keep getting the error of
#include <map>
using namespace std;
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
std::map<ListNode, int> history; \\ so here history is created to be an object of type map
ListNode *current = head;
if(head == NULL) {
return nullptr;
} else {
while(current->next) {
history.insert(make_pair(current, current->val)); \\ this line has the error of no matching member function for call to "insert"
if(history.count(current->next)) {
return current->next;
}
}
}
return nullptr;
}
};
could someone points out what is wrong here? or maybe my understanding in the c map class?
sorry I am pretty new to c and my uses of c terminology might not even be right.
thank you
CodePudding user response:
std::map<ListNode, int> history;
This map's key is a ListNode
.
ListNode *current = head;
current
is a ListNode *
, a pointer to a ListNode
.
history.insert(make_pair(current, current->val));
This attempts to insert a ListNode *
key into a map whose key is a ListNode
. This is ill-formed. If a map's key is an int
, an inserted key must be an int
. If the map's key is a ListNode
the inserted key must be a ListNode
. If the map's key is a ListNode *
the inserted key must be a ListNode *
.
Either your map's key is wrong, or your insert()
call is wrong.
P.S. You appear to be using an outdated C textbook to learn C , or an old C compiler that does not implement the current C standard. Modern C uses a cleaner "uniform initialization" syntax with insert()
instead of std::make_pair
. You should see if you can find a more recent textbook and/or compiler, that support modern C .