简体   繁体   中英

Use STL Containers with Struct

I want to store the address of each of the items of my linked list represented by this struct:

struct Node
   {
       int data;
       Node* next;
   };

I made an unordered set for this as:

unordered_set<Node*> h;

I defined the iterator as

unordered_set <Node*>::iterator got = h.find (&headB);

This naturally threw a lot of compiler errors. Reading up on forums, I realized that this was wrong because since Node isnt a standard data type, this iterator wouldnt work. Reading up more, I also saw somewhere that I also needed to define an operator for this implementation. I searched a lot on Stack Overflow but didnt find anything that answers this question.

So basically, I just want to know how do we make struct's work with any STL containers and iterators: How do we define containers and implement algorithms ( insert, search, deletion on them)

You are inserting and finding incorrectly. Your elements are of type Node* .

You have an "address of" operator ( & ) before Your elements. Which means You are trying to add a Node** , which is the incorrect type. So the compiler is saying:

prog.cpp:67:24: error: no matching function for call to ‘std::unordered_set<Node*>::insert(Node**)’

The correct way is to add an element of the correct type, which is Node* , by removing the address of operator ( & );

Unless You wanted the address of a pointer, then You need the container to store Node**

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