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

This topic is 3853 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites
I assume you return by value (
T operator[](int)
). Try returning by reference (
T& operator[](int)
), thus allowing you to modify the element.

##### Share on other sites
There are two versions of the [] operator; one const, and one non-const.
You need both.

##### Share on other sites
Thanks I'll try it!
How about the first thing? Specify the type, any ideas?

##### Share on other sites

to specify the type, you do this:

template <typename yourType> class yourList
{
// and here, you use "yourType" as the templated type
}

##### Share on other sites
You should look for some information on how to use 'Templates'. That should tell you everything you need to know.

Sweet! Thanks!

##### Share on other sites
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? ;)

##### Share on other sites
Quote:
 Original post by Captain PFortunately, 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.

• 10
• 40
• 15
• 10
• 23