#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <optional>
struct Item {
int a;
int b;
std::string label;
};
// Create the dataset
std::vector<Item> make_data() {
return {
{7, 2, "python"},
{8, 3, "c"},
{3, 5, "c++"},
{4, 1, "c#"},
{3, 2, "java"},
{7, 1, "go"},
{1, 2, "rust"},
};
}
// Sort by column 0, then column 1
void sort_by_two_columns(std::vector<Item>& data) {
std::sort(data.begin(), data.end(),
[](const Item& x, const Item& y) {
if (x.a != y.a)
return x.a < y.a;
return x.b < y.b;
}
);
}
// Print a single item
void print_item(const Item& item) {
std::cout << "(" << item.a << ", "
<< item.b << ", "
<< item.label << ")\n";
}
// Print all items
void print_data(const std::vector<Item>& data) {
for (const auto& item : data) {
print_item(item);
}
}
// Find the first item with a matching label
std::optional<Item> find_by_label(const std::vector<Item>& data,
const std::string& label) {
for (const auto& item : data) {
if (item.label == label)
return item;
}
return std::nullopt;
}
// Return all items with a matching first column
std::vector<Item> filter_by_first_column(const std::vector<Item>& data, int value) {
std::vector<Item> result;
for (const auto& item : data) {
if (item.a == value)
result.push_back(item);
}
return result;
}
int main() {
auto data = make_data();
sort_by_two_columns(data);
print_data(data);
std::cout << "\nSearching for 'java':\n";
if (auto found = find_by_label(data, "java")) {
print_item(*found);
}
std::cout << "\nFiltering items where a == 7:\n";
auto filtered = filter_by_first_column(data, 7);
print_data(filtered);
}
/*
run:
(1, 2, rust)
(3, 2, java)
(3, 5, c++)
(4, 1, c#)
(7, 1, go)
(7, 2, python)
(8, 3, c)
Searching for 'java':
(3, 2, java)
Filtering items where a == 7:
(7, 1, go)
(7, 2, python)
*/