To insert an item at a specific index in a Vector in C++, you can use the insert()
method. This method inserts elements into the Vector at the specified position.
In this example,
insert()
method to insert the integer at the desired index.#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int newNumber = 10;
int index = 2; // Index to insert
numbers.insert(numbers.begin() + index, newNumber);
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
1 2 10 3 4 5
In this example,
insert()
method to insert the string at the desired index.#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> words = {"apple", "banana", "orange"};
std::string newWord = "grape";
int index = 1; // Index to insert
words.insert(words.begin() + index, newWord);
for (const std::string& word : words) {
std::cout << word << " ";
}
return 0;
}
apple grape banana orange
In this tutorial, we learned How to Insert an Item at Specific Index in a Vector in C++ language with well detailed examples.