What’s the standard or common data structure for a list of objects in C++?

Posted on In QA

In C++, what’s the standard or common data structure for a list of objects?

In C++, the common data structure for a sequence (“list”) of objects may be std::vector.

A vector is a dynamically resizable array. It is “The most extensively used container in the C++ Standard Library …, offering a combination of dynamic memory management and efficient random access.” — Lock-free Dynamically Resizable Arrays

And vector is the default first data structure you should think about for a problem for its compactness and efficiency. Bjarne Stroupstrup has an excellent talk on this, check it out.

From the standard draft C++11 (with important parts highlighted):

A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously

Check the standard draft section 23.3.6 for more details.

One usage example from cppreference.com:

#include <iostream>
#include <vector>
 
int main()
{
    // Create a vector containing integers
    std::vector<int> v = {7, 5, 16, 8};
 
    // Add two more integers to vector
    v.push_back(25);
    v.push_back(13);
 
    // Iterate and print values of vector
    for(int n : v) {
        std::cout << n << 'n';
    }
}

Run it on Caliru.

Leave a Reply

Your email address will not be published. Required fields are marked *