Library contents

C++ Vector copy construction

Capture the current guest list before accepting late additions.

A simple example

Vector copy construction

  1. Start with Original list A, B
  2. Do this Copy it, then append C to the original
  3. Result Copy still has A, B
The list of elements in the earlier snapshot is unaffected by the later append.

Syntax

C++ syntax
const auto printed = draft
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

Freeze the guest list used to print badges

A school prints badges from a draft guest list. A late guest joins after printing starts, so the team keeps a snapshot that records exactly how many badges belonged to the original run.

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

int main() {
    std::vector<std::string> draft{"Mira", "Sam"};
    const auto printed = draft;
    draft.push_back("Nia");
    std::cout << printed.size();
    return 0;
}
Output
2

The count for the original badge run remains two.

Advertisements

Freeze the morning guest list

The school prints the first two names before a late guest registers. After saving a snapshot, add the late entry only to the working list. Which names remain visible on the snapshot?

GivenSnapshot Pia, Kai · later add Mira
Worked resultPia · Kai

Save a stage checklist

A technician archives the checklist before adding a new microphone. After saving a snapshot, add the late entry only to the working list. Which names remain visible on the snapshot?

GivenSnapshot Stand, Cable · later add Mic
Worked resultStand · Cable

What to watch for

The vector copies its elements. Pointer elements would still refer to shared objects.

Documentation for Vector copy construction