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++
// C++ program to demonstrate changing an element in a // vector #include <iostream> #include <vector> using namespace std;
int main()
{ // Initialize a vector
vector< int > vec = { 1, 2, 3, 4, 5 };
// Output the original vector
cout << "Original vector: " ;
for ( int i : vec) {
cout << i << " " ;
}
cout << endl;
// Index of the element to be changed
int index = 2;
// New value to be set
int newValue = 10;
// Check if the index is within range
if (index >= 0 && index < vec.size()) {
// Modify the element at the specified index
vec[index] = newValue;
}
else {
cout << "Index out of range!" << endl;
return 1;
}
// Output the modified vector
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)