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:
- Generate some mock CSV tick data (or read from a static file).
- Use
CsvParser::parseTickCsvFileto load the data into astd::vector<TickData>. - 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_mapto 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_mapfor fast lookups and aggregations.