tinycodinglm / cpp /cpp-stl-algorithms.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.1 kB
opencode trace
System You are an expert C++ developer. You write clean, efficient, and idiomatic code.

You are an expert C++ developer. You write clean, efficient, and idiomatic code.

User

Master C++ STL algorithms: sort, transform, accumulate, and parallel execution

Assistant

#include <algorithm>
#include <numeric>
#include <vector>
#include <execution>
#include <ranges>
#include <iostream>
#include <random>

int main() {
std::vector<int> nums = {5, 3, 1, 4, 2, 8, 7, 6};

markdown
// Sort
std::sort(nums.begin(), nums.end());
std::sort(nums.begin(), nums.end(), std::greater<int>());

// Binary search (requires sorted)
std::sort(nums.begin(), nums.end());
bool found = std::binary_search(nums.begin(), nums.end(), 5);

// Transform
std::vector<int> doubled(nums.size());
std::transform(nums.begin(), nums.end(), doubled.begin(), [](int x) { return x * 2; });

// Accumulate
int sum = std::accumulate(nums.begin(), nums.end(), 0);
int product = std::accumulate(nums.begin(), nums.end(), 1, std::multiplies<int>());

// Remove-erase idiom
nums.erase(std::remove_if(nums.begin(), nums.end(), [](int x) { return x % 2 == 0; }), nums.end());

// Partial sort
std::partial_sort(nums.begin(), nums.begin() + 3, nums.end());

// nth_element
std::nth_element(nums.begin(), nums.begin() + nums.size()/2, nums.end());

// Parallel algorithms (C++17)
std::vector<int> large(1000000);
std::iota(large.begin(), large.end(), 0);
std::sort(std::execution::par, large.begin(), large.end());

// C++20 ranges
auto evens = large | std::views::filter([](int x) { return x % 2 == 0; })
                    | std::views::take(10);

for (auto v : evens) std::cout << v << " ";
std::cout << "\n";

return 0;

}