tinycodinglm / cpp /cpp20-003.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.21 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Explain C++20 ranges with practical examples

Assistant

C++20 Ranges:

Basic View Composition:

cpp
#include <ranges>

std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto result = v
    | std::views::filter([](int x) { return x % 2 == 0; })
    | std::views::transform([](int x) { return x * x; })
    | std::views::take(3);

// result: 4, 16, 36

Common Views:

cpp
// Filter
auto evens = v | std::views::filter([](int x) { return x % 2 == 0; });

// Transform
auto squared = v | std::views::transform([](int x) { return x * x; });

// Take/Skip
auto first5 = v | std::views::take(5);
auto after5 = v | std::views::drop(5);

// Reverse
auto rev = v | std::views::reverse;

// Elements (for tuples)
std::vector<std::tuple<int, std::string>> data;
auto names = data | std::views::elements<1>;

// Keys/Values (for maps)
std::map<int, std::string> m;
auto keys = m | std::views::keys;
auto vals = m | std::views::values;

Custom View:

cpp
auto my_view = [](int start, int step) {
    return std::views::iota(start)
         | std::views::stride(step);
};

// Usage
for (int x : my_view(0, 3) | std::views::take(5)) {
    std::cout << x << " ";  // 0 3 6 9 12
}

Join View:

cpp
std::vector<std::vector<int>> nested = {{1,2}, {3,4}, {5,6}};
auto flat = nested | std::views::join;
// 1, 2, 3, 4, 5, 6

Split View:

cpp
std::string csv = "one,two,three";
auto parts = csv | std::views::split(',');
// "one", "two", "three"