Is it possible to make a class like this...
So I want to make a class for linked lists.
When I define it I want to make something similiar to what the standard vector-class does!
ListClass <int> list; // where <xxx> = is the type
Then be able to access the elements like this: list[x]
I've no clue how to make the first thing mentioned!
I succeeded halfway with the second thing by overloading the operator [] but I can still only retrieve data!
like... (for an int linked list)
a = list[0]; // OK!
list[0] = 20; // (gives me error, which in fact makes sense, but how should I make it work?)
Please help me out
cheers
I assume you return by value (
T operator[](int)
). Try returning by reference (T& operator[](int)
), thus allowing you to modify the element.
to specify the type, you do this:
template <typename yourType> class yourList
{
// and here, you use "yourType" as the templated type
}
You should look for some information on how to use 'Templates'. That should tell you everything you need to know.
Fortunately, such a container class already exists. It's called std::list. That sure saves you the hassle of writing one yourself, doesn't it? ;)
Quote:Original post by Captain P
Fortunately, such a container class already exists. It's called std::list. That sure saves you the hassle of writing one yourself, doesn't it? ;)
Sort-of-unfortunately, the std::list does not provide operator[]. But there is a good reason for that: operator[] is not a sensible operation for linked lists.. To get the Nth element requires a traversal from the beginning of the list, which breaks the expectation of "array indexing" and may encourage people to unwittingly write slow (in the big-O sense) code.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement