Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of std::list c [closed]

Tags:

c++

arrays

list

I can't find any human explaination for this: how can I create an array of lists like

std::list<int> mylist[size] ?

If I put this in my program it compiles but creates some problems since it doesn't execute any code (the rest of the code works just fine if I write mylist w/out [size])

I was reading somewhere that using primitive arrays of C is not recommended; what are the alternatives?

Thanks sorry for newbness

like image 952
Marco Pietrosanto Avatar asked Jul 27 '13 12:07

Marco Pietrosanto


1 Answers

Your declaration is incorrect, and not supported in C++. You're trying to declare a variable-sized array at run-time, which IS a C99 feature, but is not in C++. See here: Array size at run time without dynamic allocation is allowed?

You have this:

std::list<int> mylist[size]

What you need is this:

std::list<int> mylist[] = new std::list<int>[size];

But this is still a bad idea, as you need to de-allocate it later with delete []. As others have said, you can do it a couple of different ways, all of which are better for c++:

std::list< std::list< int > > myListOfLists;      // Linked list of linked lists
std::vector< std::list< int > > myVectorOfLists;  // Better, a vector is more like an array
std::array<std::list<int>, 10> this_would_do;     // From above, only works if you know the array size at compile-time

I hope this helps and is clear for you.

like image 156
Kevin Anderson Avatar answered Oct 14 '22 07:10

Kevin Anderson