arraylist equivalent cpp

To create an ArrayList equivalent in C++, you can use the std::vector class from the C++ Standard Library. The std::vector class provides dynamic array-like functionality and is a commonly used container in C++.

Here are the steps to create an ArrayList equivalent in C++ using std::vector:

  1. Include the necessary header file:
#include <vector>

This includes the header file that contains the definition of the std::vector class.

  1. Declare a vector:
std::vector<int> arrayList;

This declares a vector named arrayList that can store elements of type int. You can replace int with any other data type as needed.

  1. Add elements to the vector:
arrayList.push_back(10);
arrayList.push_back(20);
arrayList.push_back(30);

This adds elements to the vector using the push_back() function. The push_back() function appends an element to the end of the vector.

  1. Access elements in the vector:
int element1 = arrayList[0];
int element2 = arrayList.at(1);

You can access elements in the vector using the subscript operator [] or the at() function. The subscript operator provides direct access to the element at a specified index, while the at() function provides bounds checking and throws an exception if the index is out of range.

  1. Get the size of the vector:
int size = arrayList.size();

The size() function returns the number of elements in the vector.

  1. Iterate over the vector:
for (int i = 0; i < arrayList.size(); i++) {
    int element = arrayList[i];
    // Do something with the element
}

You can iterate over the vector using a loop and access each element using the subscript operator.

  1. Remove elements from the vector:
arrayList.pop_back();

The pop_back() function removes the last element from the vector.

  1. Clear the vector:
arrayList.clear();

The clear() function removes all elements from the vector and makes it empty.

By following these steps, you can create an ArrayList equivalent in C++ using the std::vector class.