I made an inmplementation of doubly linked list as class in C++
In main.cpp I'm pushing objects of other class into this list like this
list.insertBack(ClassA(name, description));
But after that I need to change a certain field of this object, for example perform a method that changes population. For that I need to somehow adress this object from the list like I would do with a regular array (smth like a[i]
). For that I need a special method/function in my List class. How can I implement this?
You just need to provide a operator[]
for your class:
template<class T>
class List {
// your private interface
public:
// your other public interface
T& operator[](unsigned int i)
{
Node* n = this->head;
for (; i>0; --i)
{
n = n->next;
}
return n->data;
}
};
In your main you can then simply use it like
int main() {
List<double> l;
l.insertBack(0.0);
l.insertBack(1.0);
l.insertBack(2.0);
l.insertBack(3.0);
std::cout << l[2] << std::endl;
}
Note that you might also want a const
version of this function. Here is a demo.
Note: As pointed out by @Botje, you might also want do some sanity checks on the input. If i
is equal or larger than the number of existing nodes, my code snippet dereferences a nullptr
and you get undefined behavior.