0

I want to write a class of a generic sorted list, which will always be able to insert an object to the list no matter how many objects it has already. so basically I have a homework to write a list that would act just like the STL list, which has no size limitation.

this is the class that I am thinking of:

template <class T>
class SortedList
{
 T* data;
 int current_size;
 int max_size;
public:
//some functions
};

if I set the max_size to 10 for example and then when ever the current_size==max_size to expand the list size . How can I do that? If I was writing this in c I would simply use realloc, however it's not possible here.

So is there a way to expand the list in c++, or a way that it could have an unlimited size?

Raea6789
  • 141
  • 1
  • 11
  • why does it have a `max_size` member in the first place? You would need to do something extra to limit the size of the list, but to have no limit you just add nodes until you run out of memory – 463035818_is_not_an_ai Jun 07 '21 at 11:37
  • 1
    You have to `new` the new, larger list, copy/move the objects to the new list, then `delete` the old list. But why go through all this trouble, when you already have `std::vector`, that does exactly that, and does more stuff for you, correctly, like properly constructing each value in the list (while the naive `new`-based approach will immediately construct a bunch of new list members, right off the bat)? – Sam Varshavchik Jun 07 '21 at 11:38
  • @SamVarshavchik I can't use std::vector because it's a homework for university and this is what they want... so there isn't any other way than making a new list copy the data and delete the old list? – Raea6789 Jun 07 '21 at 11:42
  • 1
    That's correct. This is exactly how `std::vector` does this. See also: https://stackoverflow.com/questions/3482941/how-do-you-realloc-in-c and additionally, after all, `realloc` in C does exactly the same thing: `malloc` the new array, copy its contents, and `free` the old one. You just have to do the same thing yourself, in C++. – Sam Varshavchik Jun 07 '21 at 11:49

0 Answers0