C++ vector at() function
Example
Get an element from a vector at index position 2:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars.at(2);
Try it Yourself »
Definition and Usage
The at()
function returns a reference to an element in a vector.
Tip: Values can be assigned to the reference, which will change the vector.
Syntax
vector.at(size_t position);
The size_t
data type is a non-negative integer.
Parameter Values
Parameter | Description |
---|---|
position | Required. An integer specifying a position in the vector. |
Technical Details
Returns: | A reference to the element in the given index position in the vector. |
---|
More Examples
Example
Change an element in a vector at index position 2:
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.at(2) = "Toyota";
for (string car : cars) {
cout << car << " ";
}
Try it Yourself »
Related Pages
Read more about vectors in our Vector Tutorial.