C++ std::vector::at and size
Read one name from an ordered roster after checking its length.
A simple example
std::vector::at and size
- Start with A, B, C
- Do this Read the second element
- Result B
Syntax
names.at(index)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonRead the second name on the pickup roster
A teacher calls children in their recorded pickup order. The office asks for the second name on the roster, so the teacher checks that the list contains at least two entries before reading it.
ResultMira
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> names{"Asha", "Mira", "Sam"};
if (names.size() >= 2) std::cout << names.at(1);
return 0;
}
Mira
Mira occupies the second position on the three-person roster.
Advertisements
Prepare the next workshop roster
A teacher reads a workshop roster in arrival order. Who or what occupies the second position? Count from the front of the list.
GivenMira · Ivo · Bea
Worked resultIvo
Work from the delivery round
A courier has three labelled stops in route order. Who or what occupies the second position? Count from the front of the list.
GivenPark · Mill · Pier
Worked resultMill
What to watch for
at checks bounds and throws std::out_of_range if the position is invalid.