Is it possible to make a class like this...

Started by
7 comments, last by Zahlman 16 years, 5 months ago
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
Problems every where
Advertisement
I assume you return by value (
T operator[](int)
). Try returning by reference (
T& operator[](int)
), thus allowing you to modify the element.

To make it is hell. To fail is divine.

There are two versions of the [] operator; one const, and one non-const.
You need both.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Thanks I'll try it!
How about the first thing? Specify the type, any ideas?


Problems every where

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.
Sweet! Thanks!
Problems every where
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? ;)
Create-ivity - a game development blog Mouseover for more information.
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