← C++

C++ · 16 / 24

Process data with span, string_view and ranges

Process orders without unnecessary input copies and explain when a borrowed view becomes invalid.

  • Medium
  • Intermediate
  • 60 min

Prerequisites: Strings, vectors and standard algorithms, Headers, CMake and first unit tests, Ownership, lifetime and move semantics, Use templates and concepts in practice

In this tutorial
  1. Build the independent package
  2. Separate ownership from views
  3. Filter and transform
  4. Use understandable fixtures
  5. Check the returned value's lifetime
  6. Add another query
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20, CMake 3.25 or later, CTest and Python 3. Extract the ZIP into a new folder. python3 run_checks.py checks example and solution in a temporary copy and preserves your files. Run python3 verify.py for your own build. The demo is then available at build/order_lab. No additional libraries are required. The documented commands were checked on Linux.

Verified on 2026-10-21 on Linux x86_64. C++20 build, filtering results, empty inputs and independently owned return values. The exercise counts urgent open orders. No benchmark or automatic proof of all possible lifetime errors.

An order filter needs read access to a list and search text. It does not need to own their storage. In this example a vector owns the orders. span describes a readable slice, string_view the query and a ranges pipeline the selection. The result owns its IDs. This boundary prevents callers from receiving a view into destroyed data.

Package contents and individual files

01Build the independent package

Extract cpp-16.zip. Running python3 verify.py builds a demo and two test programs. C++20 is explicitly required. GCC and Clang warnings are treated as errors so issues such as suspicious references to temporaries are caught during compilation.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(cpp_16 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
enable_testing()
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
  add_compile_options(-Wall -Wextra -Wpedantic -Werror)
endif()
add_executable(order_lab main.cpp)
add_executable(lesson_tests tests.cpp)
add_test(NAME lesson_tests COMMAND lesson_tests)
set_tests_properties(lesson_tests PROPERTIES TIMEOUT 30)
add_executable(exercise_solution solution.cpp)
add_test(NAME exercise_solution COMMAND exercise_solution)
set_tests_properties(exercise_solution PROPERTIES TIMEOUT 30)
Expected result

CTest reports two passing test programs.

02Separate ownership from views

Order owns its title as std::string. matchingIds accepts std::span<const Order> and std::string_view. Both parameters borrow storage. The filtered view is consumed inside the function. The returned vector<int> owns its elements. Do not grow or destroy the original vector while any borrowed view is still in use.

order.hpp · cppOpen file
#pragma once
#include "result.hpp"
#include <algorithm>
#include <ranges>
#include <set>
#include <span>
#include <string_view>
#include <vector>

namespace orders {
enum class Status { open, done };
struct Order {
  int id;
  std::string title;
  int priority{0};
  Status status{Status::open};
  bool operator==(const Order &) const = default;
};
inline Result<Done> validate(const Order &order) {
  const bool blank = std::ranges::all_of(order.title, [](char c) {
    return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  });
  if (order.id < 1 || order.id > 1000000 || order.title.empty() ||
      order.title.size() > 80 || blank || order.priority < 0 ||
      order.priority > 2 ||
      (order.status != Status::open && order.status != Status::done))
    return Error{ErrorCode::invalid, "ID 1..1000000, title 1..80 UTF-8 bytes, "
                                     "priority 0..2 and valid status required"};
  return Done{};
}
inline Result<Done> validateBatch(std::span<const Order> batch) {
  if (batch.size() > 1000)
    return Error{ErrorCode::invalid, "At most 1000 orders are allowed"};
  std::set<int> ids;
  for (const auto &order : batch) {
    auto result = validate(order);
    if (!succeeded(result))
      return std::get<Error>(result);
    if (!ids.insert(order.id).second)
      return Error{ErrorCode::duplicate, "Duplicate order ID"};
  }
  return Done{};
}
inline std::vector<int> matchingIds(std::span<const Order> values,
                                    std::string_view needle) {
  // Both views borrow their input. Consume them before the owner changes.
  auto matching =
      values | std::views::filter([needle](const Order &order) {
        return order.status == Status::open &&
               order.title.find(needle) != std::string::npos;
      }) |
      std::views::transform([](const Order &order) { return order.id; });
  return {matching.begin(), matching.end()};
}
inline Result<Done> replaceValidated(std::vector<Order> &current,
                                     std::span<const Order> incoming) {
  auto result = validateBatch(incoming);
  if (!succeeded(result))
    return std::get<Error>(result);
  std::vector<Order> candidate(incoming.begin(), incoming.end());
  // Validation and allocations precede this non-throwing commit point.
  current.swap(candidate);
  return Done{};
}
} // namespace orders
Expected result

No borrowed view escapes the function.

03Filter and transform

Run ./build/order_lab. filter keeps only open orders whose title contains the query. transform reads each ID. Matching is deliberately case-sensitive. An empty query matches every open order. The pipeline is lazy and becomes materialized when the result vector is constructed.

main.cpp · cppOpen file
#include "test_support.hpp"
int main() {
  for (int id : orders::matchingIds(samples(), "Deliver"))
    std::cout << "Open delivery: " << id << '\n';
}
Expected result

Open delivery: 1

04Use understandable fixtures

The three synthetic orders differ in title, priority and status. A completed order also contains Deliver, so the test detects whether the status filter is actually applied. require throws on failure and still works when a release build removes ordinary assert calls.

test_support.hpp · cppOpen file
#pragma once
#include "order.hpp"
#include <iostream>
#include <stdexcept>
inline void require(bool condition, const char *message) {
  if (!condition)
    throw std::runtime_error(message);
}
inline std::vector<orders::Order> samples() {
  return {{1, "Deliver motors", 2},
          {2, "Move pallets", 0},
          {3, "Deliver sensors", 1, orders::Status::done}};
}
Expected result

Only the first order satisfies both conditions.

05Check the returned value's lifetime

Tests cover empty lists, missing matches and the result after clearing the input vector. The last test demonstrates that returned IDs are independently stored. It does not prove that arbitrary span or string_view objects are automatically safe. Never dereference invalid views even in a test.

tests.cpp · cppOpen file
#include "test_support.hpp"
int main() {
  auto batch = samples();
  require(orders::matchingIds(batch, "Deliver") == std::vector<int>{1},
          "filter open titles");
  require(orders::matchingIds({}, "").empty(), "empty input");
  require(orders::matchingIds(batch, "absent").empty(), "no match");
  auto owned = orders::matchingIds(batch, "");
  batch.clear();
  require(owned == std::vector<int>({1, 2}), "returned IDs own their memory");
  std::cout << "ranges and ownership checks passed\n";
}
Expected result

ranges and ownership checks passed

06Add another query

Attempt the exercise before reading the solution. It uses ranges::count_if for open orders with priority 2. Counting alone does not require an additional result vector. Check regular data, empty input and a completed urgent order.

solution.cpp · cppOpen file
#include "test_support.hpp"
std::size_t countUrgent(std::span<const orders::Order> values) {
  return std::size_t(std::ranges::count_if(values, [](const auto &order) {
    return order.status == orders::Status::open && order.priority == 2;
  }));
}
int main() {
  require(countUrgent(samples()) == 1, "one open urgent order");
  require(countUrgent({}) == 0, "empty input");
  std::vector<orders::Order> completed{
      {1, "Completed", 2, orders::Status::done}};
  require(countUrgent(completed) == 0, "done is excluded");
}
Expected result

The sample contains exactly one open urgent order.

Your exercise

Write countUrgent(span<const Order>). Count only open orders with priority 2 without changing the input. Add checks for an empty list and a completed urgent order.

Show the solution and explanation

solution.cpp combines both conditions in one predicate and returns a size_t count. An empty range yields 0. A done order does not count even at priority 2. Run python3 verify.py to check example and solution together.

solution.cpp · cppOpen file
#include "test_support.hpp"
std::size_t countUrgent(std::span<const orders::Order> values) {
  return std::size_t(std::ranges::count_if(values, [](const auto &order) {
    return order.status == orders::Status::open && order.priority == 2;
  }));
}
int main() {
  require(countUrgent(samples()) == 1, "one open urgent order");
  require(countUrgent({}) == 0, "empty input");
  std::vector<orders::Order> completed{
      {1, "Completed", 2, orders::Status::done}};
  require(countUrgent(completed) == 0, "done is excluded");
}

Project context and sources

Independent teaching project using FactoryForge's logistics theme. The existing FactoryForge source revision provides architectural context. SQLite, networking and import features introduced here belong to the teaching project. Order Lab JSON is a separate format.