Just getting back into using C++ and trying to convert a simple Java program I wrote recently.
What's the preferred equivalent to the Java ArrayList in C++?
There's no such thing in the standard C library. People usually roll their own. While the terms vector and ArrayList usually refer to the same datastructure (resizable array), a linked list is something completely different.
Arraylist in C++ can easily be accessed using the indexing through integers. But now the arraylist is being replaced with List in C++ over the years. The list is a sequential container which holds the data of the same type.
An ArrayList is never "full". And there is no default value either, the default is the list is "empty".
C++ allows us a facility to create an array of lists. An array of lists is an array in which each element is a list on its own. Syntax: list<dataType> myContainer[N];
Use the std::vector
class from the standard library.
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With