To access items in a vector in C++, you can use indexing and iterators.
In this example,
header to use the vector container.myVector
containing some elements.[]
and specify the index of the element we want to access.#include <iostream>
#include <vector>
int main() {
std::vector<std::string> myVector = {"apple", "banana", "cherry", "date"};
// Access single element by index (e.g., index 1)
std::string accessedElement = myVector[1];
// Print accessed element
std::cout << accessedElement << std::endl;
return 0;
}
banana
In this example,
header to use the vector container.myVector
containing some elements.[]
to access multiple elements from the vector.#include <iostream>
#include <vector>
int main() {
std::vector<std::string> myVector = {"apple", "banana", "cherry", "date"};
// Access multiple elements by indices (e.g., indices 0 to 2)
std::vector<std::string> accessedElements(myVector.begin(), myVector.begin() + 3);
// Print accessed elements
for (const auto& element : accessedElements) {
std::cout << element << "\n";
}
return 0;
}
apple banana cherry
In this example,
and
headers to use the vector container and IO operations.myVector
containing numeric elements.#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector = {10, 20, 30, 40, 50};
// Access elements using iterators
for (auto it = myVector.begin(); it != myVector.end(); ++it) {
std::cout << *it << "\n";
}
return 0;
}
10 20 30 40 50
In this tutorial, we learned How to Access Items in a Vector in C++ language with well detailed examples.