How to Change an Element by Index in a Vector in C++?
Last Updated :
14 Feb, 2024
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++.
Example:
Input:
myVector ={1,2,3,4,5}
Output:
myVector ={1,2,7,4,5}
// replaced element at index 2 with 7
Change a Specific Element in a Vector by Index
To replace a specific element in a vector using its index, we can use the [] array subscript operator. It is used with the index and the vector name and we directly assign the new value using the assignment operator.
C++ Program to Change a Specific Element in a Vector by Index
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5 };
cout << "Original vector: " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
int index = 2;
int newValue = 10;
if (index >= 0 && index < vec.size()) {
vec[index] = newValue;
}
else {
cout << "Index out of range!" << endl;
return 1;
}
cout << "Modified vector: " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Output
Original vector: 1 2 3 4 5
Modified vector: 1 2 10 4 5
Time Complexity : O(1)
Auxilary Space: O(1)
Share your thoughts in the comments
Please Login to comment...