Files
Code/cplusplus/geminitutorial/tutorial2/tutorial-2.2-plan.md
2026-01-06 15:05:27 +00:00

2.6 KiB

Tutorial 2.2 Plan: Modern STL Containers & Algorithms

Objective: Use the workhorse containers and algorithms with a focus on performance. The project involves parsing mock CSV tick data using algorithms and lambdas to perform queries.


1. Project Setup

We will continue working within the tutorial-2 directory. No new directory creation is needed.

2. Defining Tick Data Structure

We'll define a simple struct to represent a tick, containing a timestamp, price, and volume.

File: tutorial-2/src/TickData.h

#pragma once

#include <string>
#include <chrono>

struct TickData {
    std::chrono::system_clock::time_point timestamp;
    double price;
    long volume;

    // Optional: for easy printing/debugging
    std::string toString() const;
};

3. CSV Parsing Utility

We'll implement a function to parse a single line of CSV data into a TickData object. This will involve string manipulation and conversion. std::string_view will be crucial here for zero-copy parsing.

File: tutorial-2/src/CsvParser.h

#pragma once

#include "TickData.h"
#include <string>
#include <vector>

namespace CsvParser {
    TickData parseTickCsvLine(std::string_view line);
    std::vector<TickData> parseTickCsvFile(std::string_view filename);
} // namespace CsvParser

File: tutorial-2/src/CsvParser.cpp

#include "CsvParser.h"
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <iostream> // For error reporting

// Implement parseTickCsvLine and parseTickCsvFile

4. Main Application: Parsing and Querying

In tutorial-2/src/main.cpp, we will:

  1. Generate some mock CSV tick data (or read from a static file).
  2. Use CsvParser::parseTickCsvFile to load the data into a std::vector<TickData>.
  3. Perform various queries using modern STL algorithms and lambdas:
    • Find the highest price.
    • Calculate the total volume.
    • Filter ticks above a certain price.
    • Find the average price within a time range.
    • Use std::unordered_map to aggregate volume by some key (e.g., minute of the hour).

5. Updating the Build System

Modify tutorial-2/CMakeLists.txt to include TickData.cpp and CsvParser.cpp (if needed, TickData might just be a header). Ensure proper linking.

6. Summary and Key Takeaways

This tutorial will provide hands-on experience with:

  • Efficient string handling using std::string_view.
  • Storing structured data in std::vector.
  • Performing data transformations and queries using STL algorithms and lambdas.
  • Using std::unordered_map for fast lookups and aggregations.