Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to implement a linked list in C++?

+4 votes
asked Nov 6, 2021 by Areeb Sherjil (1,960 points)
I am trying to implement a linked list. I have a class called Truckload in which I made another class called Iterator.

class Truckload
{
public:  class Iterator;
  Iterator getIterator()const;};

This is defined outside the class like this:

class Truckload::Iterator

{

public:

SharedBox getFirstBox();

SharedBox getNextBox();

SharedBox findLargestBox(const Truckload& truckload)const;

SharedBox findSmallestBox(const Truckload& truckload)const;

private:

Package* m_head;

Package* m_current;

friend class Truckload;

explicit Iterator(Package* head) :m_head{ head }, m_current{ nullptr }{}

};

The problem is how can I access 'findLargestBox' from the int main function?

this is inside int main():

(load1 is a Truckload object)

auto it1{ load1.getIterator() }; // this gives an error use of undefined type Truckload::Iterator
  SharedBox largestBox{ it1.findLargestBox() };

1 Answer

0 votes
answered Nov 6, 2021 by Peter Minarik (84,720 points)
selected Nov 6, 2021 by Areeb Sherjil
 
Best answer

Using the Iterator

You need to dereference the iterator to get the item it points to.

So what you need should be as simple as

it1->findLargestBox()

Notice the -> instead of .

List or Vector?

You can just use the existing C++ implementation: std::list

Also, are you sure you need a linked list and not a dynamic array (std::vector)?

What are the properties that you need for this container to have? (What makes the linked list the best solution for your needs?)

commented Nov 6, 2021 by Areeb Sherjil (1,960 points)
edited Nov 6, 2021 by Areeb Sherjil
Hi, I can use a vector but for now I am leaning about linked lists.

The problem is here; in the int main()
 auto it1{ load1.getIterator() }; Compiler Error C2027
 /* this gives an error and you can't seem to use the '->' operator because that gives another error: operator -> or ->* applied to instead of to a pointer type*/

 SharedBox largestBox{ it1->findLargestBox() };//Compiler Error C2027
 /*this does not work either same error as before despite the fact that Iterator class is defined fully*/

UPDATE: I fixed the problem by defining the findLargest and findSmallest functions in main, they were defined incorrectly before in the wrong .cpp file. Thanks for the help!
commented Nov 6, 2021 by Peter Minarik (84,720 points)
I'm glad you're sorted.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...