interstar
interstar

Reputation: 27186

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

Upvotes: 94

Views: 178515

Answers (3)

Pavan Chandaka
Pavan Chandaka

Reputation: 12751

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.

Upvotes: 1

SLaks
SLaks

Reputation: 887453

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

Upvotes: 107

Steve Townsend
Steve Townsend

Reputation: 54148

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

Upvotes: 69

Related Questions