• Advertisement
Sign in to follow this  

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

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

If you intended to correct an error in the post then please contact us.

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 this post


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

Share this post


Link to post
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 this post


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

Share this post


Link to post
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 this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement