Library contents

C++ std::vector::erase

Remove the item at a chosen position from a packing list.

A simple example

std::vector::erase

  1. Start with A, B, C
  2. Do this Remove the middle item
  3. Result A, C
After removal the next item follows A directly.

Syntax

C++ syntax
items.erase(position)
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

Take a cancelled item off a packing list

A customer cancels the second item on an order after the packing list has printed. The picker uses its position to remove exactly that item and reads the removed label back to the customer.

ResultSoap
lesson.cpp
#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> items{"Tea", "Soap", "Rice"};
    auto removed = items.at(1);
    items.erase(items.begin() + 1);
    std::cout << removed;
    return 0;
}
Output
Soap

Soap is the item removed from the second position.

Advertisements

Prepare the next workshop roster

A teacher reads a workshop roster in arrival order. The middle entry cancels and is removed from the plan. Which two entries still appear, in order?

GivenMira · Ivo · Bea
Worked resultMira · Bea

Work from the delivery round

A courier has three labelled stops in route order. The middle entry cancels and is removed from the plan. Which two entries still appear, in order?

GivenPark · Mill · Pier
Worked resultPark · Pier

What to watch for

erase returns the next iterator. Copy the label before erasure if the receipt needs the removed value.

Documentation for std::vector::erase