c++ vector iterator

First, we need to include the <vector> header file in order to use vectors in our C++ program.

#include <vector>

Next, we declare a vector object. Here, we create a vector of integers named myVector.

std::vector<int> myVector;

We can also initialize the vector with some values using the initializer list.

std::vector<int> myVector = {1, 2, 3, 4, 5};

To add elements to the vector, we can use the push_back() function. Here, we add the value 6 to the end of the vector.

myVector.push_back(6);

To access elements in the vector, we can use the [] operator. Here, we access the element at index 2 and assign its value to the variable value.

int value = myVector[2];

To iterate over the elements of the vector, we can use an iterator. We declare an iterator variable named it and initialize it with the begin() function, which returns an iterator pointing to the first element of the vector.

std::vector<int>::iterator it = myVector.begin();

We can also use the end() function to get an iterator pointing to one past the last element of the vector. This is useful for looping over all the elements of the vector.

std::vector<int>::iterator end = myVector.end();

To iterate over the vector, we can use a loop. Here, we use a while loop to iterate from the beginning of the vector to the end.

while (it != end) {
    // Do something with the element pointed to by the iterator
    // Increment the iterator to point to the next element
    ++it;
}

Within the loop, we can access the element pointed to by the iterator using the * operator. Here, we print the value of each element.

std::cout << *it << std::endl;

To erase an element from the vector, we can use the erase() function. Here, we erase the element at index 3.

myVector.erase(myVector.begin() + 3);

To clear all the elements in the vector, we can use the clear() function.

myVector.clear();

Finally, to get the size of the vector, we can use the size() function. Here, we assign the size of the vector to the variable size.

int size = myVector.size();