Search⌘ K
AI Features

Solution: Product Inventory Lookup

Explore how to implement a product inventory lookup using modern C++ features like vectors of pairs, C++17 structured bindings, and string_view. Understand efficient iteration, data access, and condition evaluation in this practical example.

We'll cover the following...
C++ 23
// Solution: Filtering inventory using pairs and structured bindings
#include <iostream>
#include <vector>
#include <string>
#include <string_view>
#include <utility>
int main() {
// Vector storing pairs of Product Name and Price
std::vector<std::pair<std::string, double>> inventory = {
{"Headphones", 120.00},
{"USB Cable", 15.50},
{"Monitor", 250.00}
};
std::cout << "Premium Products:" << std::endl;
// Iterate using structured bindings to unpack the pair
for (const auto& [name, price] : inventory) {
// Filter based on price
if (price > 50.0) {
// Create a view to print the name without copying
std::string_view product_view = name;
std::cout << "- " << product_view << " ($" << price << ")" << std::endl;
}
}
return 0;
}
...