Library contents

C++ std::vector::at assignment

Replace one stop at a known position while preserving the rest of the route.

A simple example

std::vector::at assignment

  1. Start with A, B
  2. Do this Replace the second item with C
  3. Result A, C
Replacing one element keeps the number of elements at two.

Syntax

C++ syntax
stops.at(index) = destination
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
./lesson

Correct the second stop on a shuttle route

A dispatcher spots an outdated address at the second stop on today's shuttle route. The position on the schedule is correct, so only the destination at that position should change.

From the programstops.at(1) = "Harbor"
ResultHarbor
lesson.cpp
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> stops{"School", "Park"};
    stops.at(1) = "Harbor";
    std::cout << stops.at(1);
    return 0;
}
Output
Harbor

The second stop changes from Park to Harbor.

Advertisements

Correct a lab register

A student signed the lab sheet with a nickname. The second entry must be corrected in place. Which value occupies that position after the change?

GivenAda · Kit → replace Kit with Kiran
Worked resultKiran

Change the next stop

The shuttle cannot use the quay this morning. The second entry must be corrected in place. Which value occupies that position after the change?

GivenSchool · Quay → replace Quay with Pier
Worked resultPier

What to watch for

The checked reference must refer to an existing element. Append separately to grow a vector.

Documentation for std::vector::at assignment