user3701231 user3701231 - 1 year ago 112
C++ Question

C++ - Overloading [] operator for a list of object pointers

I have this as a member of the class TASK.

list<Stimulation*> listOfStimulations;

And the rest of my class definition;

class Task
Task(const Task& obj);
Task(const Task&& obj);
Task(string, list<Stimulation*>);
Task& operator+=( Stimulation* obj);
Stimulation* Task::operator[](int i) const;

And I want to be ale to access each Stimulation in the list.

I know I should be using vector, but using list is a requirement.

How would I overload []?

I've tried

Stimulation* Task::operator[](int i) const
list<Stimulation*>::const_iterator iter;
iter = listOfStimulations.begin();
advance(iter, i);
return *iter;

My main issue is that this code isn't letting me access the elements of my list.

For example, listOfStimulations[i] does not work, and won't let me access the function display within the Stimulations class.

Answer Source

The best way to sequentially access a list is to use its Iterator

I suggest using the data structure that fits the requirements, and not trying to use a list just because.

This is how an Iterator works;

for (std::list<T>::iterator it = mylist.begin(); it != mylist.end(); ++it)
   return *it;

Now you can use advance to get "random" access;

std::list<T>::iterator it = mylist.begin();
return *it
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download