user3701231 user3701231 - 7 days ago 7
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
{
public:
Task();
Task(const Task& obj);
Task(const Task&& obj);
Task(string, list<Stimulation*>);
Task& operator+=( Stimulation* obj);
Stimulation* Task::operator[](int i) const;
};
#endif


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

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();
std::advance(it,5);
return *it
Comments