To access an item in a C++ vector at a specific index, you can use the indexing operator ([]).
In this example,
intVector
.[]
and specify the index of the item we want to access.#include <iostream>
#include <vector>
int main() {
// Create a vector of integers
std::vector<int> intVector = {10, 20, 30, 40};
// Access item at index 2
int accessedIntItem = intVector[2];
// Print accessed integer item
std::cout << "Accessed integer item: " << accessedIntItem << std::endl;
return 0;
}
Accessed integer item: 30
In this example,
strVector
.[]
and specify the index of the item we want to access.#include <iostream>
#include <vector>
#include <string>
int main() {
// Create a vector of strings
std::vector<std::string> strVector = {"apple", "banana", "cherry", "date"};
// Access item at index 2
std::string accessedStrItem = strVector[2];
// Print accessed string item
std::cout << "Accessed string item: " << accessedStrItem << std::endl;
return 0;
}
Accessed string item: cherry
In this tutorial, we learned How to get Item in a Vector at a Specific Index in C++ language with well detailed examples.