A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/cpp/change-an-element-by-index-in-vector-in-cpp/ below:

How to Change an Element in a Vector in C++?

How to Change an Element in a Vector in C++?

Last Updated : 23 Jul, 2025

In C++, vectors are dynamic containers that store the data in a contiguous memory location but unlike arrays, they can resize themselves to store more elements. In this article, we will learn how to change a specific element by its index in a vector in C++.

The simplest way to modify an element is by directly accessing it by index using [] array subscript operator and assigning it new value using assignment operator.

C++
#include <bits/stdc++.h>
using namespace std;

int main(){
    vector<int> v = {1, 4, 2, 3, 5};
  
    // Modify the element at index 2
    v[2] = 11;

    for(auto i: v) cout << i << " ";
    return 0;
}

C++ also have other methods using which the value of an element in the vector can be updated. Let's take a look:

Using Vector at()

The vector at() method returns the reference to the element at the given index. This reference can be used to assign the new value to that element.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 4, 2, 3, 5};

    // Modify the element at index 2
  	v.at(2) = 11;
  
  	for(auto i: v) cout << i << " ";
    return 0;
}
Using Iterators

Iterators are like pointers to the elements of the vector which can be deference to update its value. The vector begin() can be incremented to point to the element at the given index.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 4, 2, 3, 5};

    // Modify the element at index 2
  	*(v.begin() + 2) = 11;
      
    for(auto i: v) cout << i << " ";
    return 0;
}
Using Vector front()

The vector front() method can be used when the first element of the vector is to be modified.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 4, 2, 3, 5};

    // Modify the first element
  	v.front() = 11;
      
    for(auto i: v) cout << i << " ";
    return 0;
}
Using Vector back()

If the last element is to be modified, then vector back() method can be used.

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v = {1, 4, 2, 3, 5};

    // Modify the last element
  	v.back() = 11;
      
    for(auto i: v) cout << i << " ";
    return 0;
}


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4