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

JavaC++Arraylist

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

Like other answers the closest one is std::vector.

But there is one important thing to consider, space complexity.

The C++ vector has compiler dependent calculation when current capacity is full. When capacity is full some compilers grow the vector capacity exponentially and some loosely exponential.

For Java arraylist, there are no exact details specified by standards for recalculating the capacity when it is full. Some have a rough calculation of 150% plus one. But not sure if that is the exact calculation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninterstarView Question on Stackoverflow
Solution 1 - JavaSLaksView Answer on Stackoverflow
Solution 2 - JavaSteve TownsendView Answer on Stackoverflow
Solution 3 - JavaPavan ChandakaView Answer on Stackoverflow