Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the C++ version of Java's ArrayList

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++?

like image 750
interstar Avatar asked Oct 19 '10 17:10

interstar


People also ask

Is ArrayList available 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.

What is the equivalent of ArrayList in C++?

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.

What is the default type of ArrayList?

An ArrayList is never "full". And there is no default value either, the default is the list is "empty".

Do we have ArrayList in C++?

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];


2 Answers

Use the std::vector class from the standard library.

like image 164
SLaks Avatar answered Oct 25 '22 07:10

SLaks


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++.

like image 42
Steve Townsend Avatar answered Oct 25 '22 08:10

Steve Townsend