Jump to content
  • Advertisement
Sign in to follow this  
ProblemBaby

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

This topic is 3942 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
I assume you return by value (
T operator[](int)
). Try returning by reference (
T& operator[](int)
), thus allowing you to modify the element.

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
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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!