C++ Vectors-Part II

E. Changing/Accessing a Vector’s Elements

Any element can be changed at any place, which is the same as accessing them. The same way that it was done with arrays, any element at any given place may be accessed by its index number.

vector<int> v = {1, 2, 3, 4};
cout << "Element at index 0 is " << v[0] << endl;

Output:

Element at index 0 is 1

The at() method, which accepts the index number as an argument and returns the element at that place, is another method that gets added for vectors.

vector<int> v = {1, 2, 3, 4};
cout << "Element at index 2 is " << v.at(2) << endl;

Output:

Element at index 2 is 3

F. Element removal from a vector

A vector’s elements can be removed in a variety of methods. When we use the pop back method to remove an element from the tail of a vector, we do so in the most cost-effective way possible. The element is popped from the back using the pop back() function, which requires no parameters.

#include <iostream>
#include <vector>
using namespace std;
 
void display(vector<int> v)
{
    cout << "The elements are: ";
    for (auto it : v)
    {
        cout << it << " ";
    }
    cout << endl;
}
 
int main()
{
    vector<int> v = {1, 2, 3, 4};
    display(v);
    v.pop_back(); //4 gets popped from the back
    display(v);
}

Output:

The elements are: 1 2 3 4 
The elements are: 1 2 3

Another method to remove an element allows us to remove it from any random position. Here, we use the erase() method. The syntax for using the erase method is

vector_name.erase(iterator);

The iterator in this case is a pointer to the location where the element is popped. Here’s an illustration of how to utilise the wipe() method:

#include <iostream>
#include <vector>
using namespace std;
 
void display(vector<int> v)
{
    cout << "The elements are: ";
    for (auto it : v)
    {
        cout << it << " ";
    }
    cout << endl;
}
 
int main()
{
    vector<int> v = {1, 2, 3, 4};
    display(v);
    v.erase(v.begin()); 
    display(v);
}

Output:

The elements are: 1 2 3 4 
The elements are: 2 3 4
Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in