Skip to content

Identity Is Not Position

The Course
•
35 min study

Suppose a user sees a list of tasks and types "complete task 2". If 2 means "the second row on screen", the answer depends on how the list was sorted when they looked and on whether anything was removed since. Sort by duration and row 2 is a different task. Delete row 1 and every later row moves up. The command now completes the wrong task, and nothing crashes to warn you.

The fix is to separate identity from position. A task's ID is part of the task: it is chosen once and never changes, whatever order you display things in. A vector index only says where an element sits right now. Today you will store and find tasks by ID, which leads to std::map in the next lesson.

Predict and run

Swapping two elements reorders the values, as a sort or a drag-and-drop in a user interface would. Which number is at index 0 afterward?

Predict before running C++
#include <iostream>
#include <utility>
#include <vector>

int main() {
    std::vector<int> ids{7, 2, 9};
    std::swap(ids[0], ids[2]);
    for (int id : ids) { std::cout << id << "\n"; }
    return 0;
}
Check your prediction
Text
9
2
7

std::swap, from <utility>, exchanges the two values it is given. Before the swap, ID 7 is at index 0. Afterward it is at index 2, but it is still 7. The value stayed the same and its position changed. Any code that remembered "index 0" to mean "task 7" is now wrong.

Removing shifts every later row

erase closes the gap it leaves, so everything after the removed element moves down one index. It takes a position rather than an index: tasks.begin() is the position of the first element, and tasks.begin() + 2 is the position of the element at index 2. Day 3 explains positions (iterators) properly; for now, read tasks.erase(tasks.begin()) as "remove the element at index 0". The program below remembers row 1, removes the first task, and reads row 1 again.

A remembered row changes meaning C++
#include <iostream>
#include <string>
#include <vector>

struct Task {
    int id;
    std::string title;
};

int main() {
    std::vector<Task> tasks{{7, "Read"}, {2, "Review"}, {9, "Practice"}};
    const std::size_t row = 1;
    std::cout << "Row 1 before: " << tasks[row].title << " (id " << tasks[row].id << ")\n";
    tasks.erase(tasks.begin());
    std::cout << "Row 1 after: " << tasks[row].title << " (id " << tasks[row].id << ")\n";
    return 0;
}
Text
Row 1 before: Review (id 2)
Row 1 after: Practice (id 9)

The index is still a valid number, so the program runs normally and prints the wrong task. This is a logic bug: defined behavior, wrong answer. Looking a task up by its ID would have found "Review" both times, because the ID moved with the task.

References into a vector are worse

You might try to keep a reference to the element instead of its index. That is a different and more serious bug. A vector stores its elements in one block of memory. When push_back needs more room than the current capacity, the vector allocates a bigger block, moves the elements there and frees the old block. Every reference, pointer and iterator into the old block now dangles: it refers to memory the vector no longer owns.

C++
std::vector<Task> tasks{{7, "Read"}};
const Task& first = tasks[0];
tasks.push_back({2, "Review"});    // May reallocate the storage.
std::cout << first.title << "\n";  // Undefined behavior if it did.

Reading through a dangling reference is undefined behavior. It may print "Read" because the freed memory has not been reused yet, which makes the bug look fixed until a different input reuses that memory. Compiled with -fsanitize=address, the read is reported as a heap-use-after-free. erase has the same effect on references to the erased element and everything after it. The safe rule for this course: do not hold a reference or iterator into a container across a change to that container. Remember the ID instead, and look the element up again after the change:

Remember the ID, not the element C++
#include <iostream>
#include <string>
#include <vector>

struct Task {
    int id;
    std::string title;
};

int main() {
    std::vector<Task> tasks{{7, "Read"}};
    const int remembered = 7;
    for (int id = 1; id <= 100; ++id) { tasks.push_back({id + 100, "Filler"}); }
    for (const Task& task : tasks) {
        if (task.id == remembered) { std::cout << "Still found: " << task.title << "\n"; }
    }
    std::cout << "Tasks stored: " << tasks.size() << "\n";
    return 0;
}
Text
Still found: Read
Tasks stored: 101

A hundred push_back calls reallocate the storage several times, but an int holding 7 cannot dangle. The fresh loop runs over the vector as it is now, so every reference it creates is valid while it is used.

How the tracker chooses IDs

The project takes IDs from its input, in the range 1 through 9999, rather than generating them:

  • Duplicates are rejected. A second record with ID 2 does not replace the first; the original task is preserved and the line counts as rejected.
  • Gaps are normal. Removing task 2 does not renumber task 3. Users who wrote down "3" can still use it.
  • Tests stay readable. With explicit IDs, a test can say "task 9 is still Review after removing task 7" without predicting what a generator would produce.

Searching a vector by ID works, but every lookup walks the whole list. The next lesson stores tasks in a std::map keyed by ID, which finds one directly and keeps the keys unique for you.

Practice

Exercise

Your turn

Write std::optional<std::string> title_of(const std::vector<Task>& tasks, int id) that returns a copy of the matching title, or nothing. Start from {7, "Read"}, {2, "Review"}, {9, "Practice"}. Look up task 2, swap the first two elements, as a user dragging Review to the top would, look it up again, print the ID at the front, erase that first element (after the swap, it is task 2) and look up both 2 and 7. Expected output:

Text
Task 2 before: Review
Task 2 after swap: Review
Removed id 2
Task 2 after removal: none
Task 7 after removal: Read
Your workspace C++
#include <iostream>
#include <optional>
#include <string>
#include <utility>
#include <vector>

struct Task {
    int id;
    std::string title;
};

// Write title_of here.

int main() {
    std::vector<Task> tasks{{7, "Read"}, {2, "Review"}, {9, "Practice"}};
    return 0;
}
Hint 1: the idea

Search by the value that represents identity, never by where the element happens to be. The same function should keep giving the same answer however the vector is reordered.

Hint 2: a first step

Write title_of first, returning std::nullopt for now, and print the first line: it should say none. Now make the loop find the task. Once Task 2 before: Review prints, add the swap and the erase from the lesson, and check that the same call still finds Review after the swap.

Show one solution
Run the solution C++
#include <iostream>
#include <optional>
#include <string>
#include <utility>
#include <vector>

struct Task {
    int id;
    std::string title;
};

std::optional<std::string> title_of(const std::vector<Task>& tasks, int id) {
    for (const Task& task : tasks) {
        if (task.id == id) { return task.title; }
    }
    return std::nullopt;
}

void show(const std::vector<Task>& tasks, int id, const char* when) {
    auto title = title_of(tasks, id);
    std::cout << "Task " << id << ' ' << when << ": " << (title ? *title : "none") << "\n";
}

int main() {
    std::vector<Task> tasks{{7, "Read"}, {2, "Review"}, {9, "Practice"}};
    show(tasks, 2, "before");
    std::swap(tasks[0], tasks[1]);
    show(tasks, 2, "after swap");
    std::cout << "Removed id " << tasks.front().id << "\n";
    tasks.erase(tasks.begin());
    show(tasks, 2, "after removal");
    show(tasks, 7, "after removal");
    return 0;
}
Text
Task 2 before: Review
Task 2 after swap: Review
Removed id 2
Task 2 after removal: none
Task 7 after removal: Read

title_of returns a copy of the title, so the result stays valid after the vector is reordered or shrunk; a reference into the vector would not. The swap moved task 2 from index 1 to index 0, yet the lookup by ID found it both times, and erasing it removed exactly that task while task 7 kept its identity. Day 3 shows how to sort with the standard algorithms; the same lookup keeps working after any reordering. The next lesson replaces this linear search with std::map, which is built for lookup by key.

Was this article helpful?

Your response is saved on this device.