Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

编程语言

C++ 示例

C++ 代码示例和Hello World演示

案例

这个案例集合中的条目

代码cpp简单

C++ Hello World

C++ Hello World程序和基本语法示例

难度

4/10

预计时间

20 min

标签

cpp, c++, programming, oop

前置条件

Basic programming concepts

cpp
// C++ Hello World Examples

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <chrono>
#include <thread>

// 1. Basic Hello World
int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

// 2. Hello World with variables and types
void helloWithVariables() {
    // Different ways to create strings
    std::string message1 = "Hello, World!";
    std::string message2("Hello, C++!");
    std::string message3 = {'H', 'e', 'l', 'l', 'o', '\0'};
    
    std::cout << message1 << std::endl;
    std::cout << message2 << std::endl;
    std::cout << message3 << std::endl;
    
    // Basic data types
    int integer = 42;
    double floating_point = 3.14159;
    char character = 'A';
    bool isBoolean = true;
    
    std::cout << "Integer: " << integer << std::endl;
    std::cout << "Double: " << floating_point << std::endl;
    std::cout << "Character: " << character << std::endl;
    std::cout << "Boolean: " << std::boolalpha << isBoolean << std::endl;
}

// 3. Hello World with functions
std::string sayHello() {
    return "Hello, World!";
}

std::string greetUser(const std::string& name) {
    return "Hello, " + name + "!";
}

void printMessage(const std::string& message) {
    std::cout << message << std::endl;
}

// 4. Hello World with references and pointers
void helloWithReferences() {
    std::string message = "Hello, C++!";
    
    // Reference
    std::string& ref = message;
    ref += " How are you?";
    std::cout << "After reference modification: " << message << std::endl;
    
    // Pointer
    std::string* ptr = &message;
    *ptr += " I'm fine!";
    std::cout << "After pointer modification: " << message << std::endl;
    
    // Const reference (efficient for large objects)
    const std::string& constRef = message;
    std::cout << "Const reference: " << constRef << std::endl;
}

// 5. Hello World with classes
class Greeter {
private:
    std::string message;
    
public:
    // Constructor
    Greeter() : message("Hello, World!") {}
    
    Greeter(const std::string& msg) : message(msg) {}
    
    // Destructor
    ~Greeter() {
        std::cout << "Greeter destroyed" << std::endl;
    }
    
    // Member function
    void greet() const {
        std::cout << message << std::endl;
    }
    
    // Overloaded function
    void greet(const std::string& name) const {
        std::cout << message << ", " << name << "!" << std::endl;
    }
    
    // Getter
    std::string getMessage() const { return message; }
    
    // Setter
    void setMessage(const std::string& msg) { message = msg; }
};

// 6. Hello World with inheritance
class BaseGreeter {
protected:
    std::string baseMessage;
    
public:
    BaseGreeter(const std::string& msg) : baseMessage(msg) {}
    virtual ~BaseGreeter() {}
    
    virtual void greet() const {
        std::cout << baseMessage << std::endl;
    }
};

class DerivedGreeter : public BaseGreeter {
private:
    std::string derivedMessage;
    
public:
    DerivedGreeter(const std::string& base, const std::string& derived)
        : BaseGreeter(base), derivedMessage(derived) {}
    
    void greet() const override {
        std::cout << baseMessage << " " << derivedMessage << std::endl;
    }
    
    void specialGreet() const {
        std::cout << "Special greeting: " << derivedMessage << std::endl;
    }
};

// 7. Hello World with templates
template<typename T>
T add(T a, T b) {
    return a + b;
}

template<typename T>
void printVector(const std::vector<T>& vec) {
    for (const auto& item : vec) {
        std::cout << item << " ";
    }
    std::cout << std::endl;
}

// 8. Hello World with STL containers
void helloWithContainers() {
    // Vector
    std::vector<std::string> greetings = {"Hello", "Hola", "Bonjour", "こんにちは", "Ciao"};
    
    std::cout << "Vector greetings:" << std::endl;
    for (const auto& greeting : greetings) {
        std::cout << greeting << ", World!" << std::endl;
    }
    
    // Map
    std::map<std::string, std::string> greetingMap = {
        {"en", "Hello"},
        {"es", "Hola"},
        {"fr", "Bonjour"},
        {"de", "Hallo"},
        {"ja", "こんにちは"}
    };
    
    std::cout << "\nMap greetings:" << std::endl;
    for (const auto& pair : greetingMap) {
        std::cout << pair.first << ": " << pair.second << ", World!" << std::endl;
    }
    
    // Pair
    std::pair<std::string, int> person("Alice", 25);
    std::cout << "\nPair: " << person.first << " is " << person.second << " years old" << std::endl;
}

// 9. Hello World with smart pointers (C++11)
#include <memory>

void helloWithSmartPointers() {
    // Unique pointer
    std::unique_ptr<std::string> ptr1 = std::make_unique<std::string>("Hello from unique_ptr!");
    std::cout << *ptr1 << std::endl;
    
    // Shared pointer
    std::shared_ptr<std::string> ptr2 = std::make_shared<std::string>("Hello from shared_ptr!");
    std::shared_ptr<std::string> ptr3 = ptr2; // Both point to same string
    
    std::cout << *ptr2 << std::endl;
    std::cout << "Reference count: " << ptr2.use_count() << std::endl;
    
    // Weak pointer
    std::weak_ptr<std::string> weakPtr = ptr2;
    std::cout << "Weak pointer reference count: " << weakPtr.use_count() << std::endl;
}

// 10. Hello World with lambda expressions (C++11)
void helloWithLambdas() {
    // Basic lambda
    auto greet = []() { return "Hello, Lambda World!"; };
    std::cout << greet() << std::endl;
    
    // Lambda with parameters
    auto greetPerson = [](const std::string& name) {
        return "Hello, " + name + "!";
    };
    std::cout << greetPerson("C++") << std::endl;
    
    // Lambda with capture
    std::string prefix = "Greetings";
    auto greetWithCapture = [prefix](const std::string& name) {
        return prefix + ", " + name + "!";
    };
    std::cout << greetWithCapture("Developer") << std::endl;
    
    // Lambda with STL algorithm
    std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
    std::for_each(names.begin(), names.end(), [](const std::string& name) {
        std::cout << "Hello, " << name << "!" << std::endl;
    });
}

// 11. Hello World with exception handling
void helloWithExceptions() {
    try {
        std::string name = "";
        if (name.empty()) {
            throw std::runtime_error("Name cannot be empty");
        }
        std::cout << "Hello, " << name << "!" << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Error: " << e.what() << std::endl;
        std::cout << "Hello, Guest!" << std::endl;
    } catch (...) {
        std::cout << "Unknown error occurred" << std::endl;
    }
}

// 12. Hello World with file I/O
#include <fstream>
#include <sstream>

void helloWithFileIO() {
    // Write to file
    std::ofstream outFile("hello.txt");
    if (outFile.is_open()) {
        outFile << "Hello, File World!" << std::endl;
        outFile << "This is a C++ file example." << std::endl;
        outFile.close();
        std::cout << "File written successfully" << std::endl;
    }
    
    // Read from file
    std::ifstream inFile("hello.txt");
    if (inFile.is_open()) {
        std::string line;
        std::cout << "\nFile contents:" << std::endl;
        while (std::getline(inFile, line)) {
            std::cout << line << std::endl;
        }
        inFile.close();
    }
    
    // String stream
    std::stringstream ss;
    ss << "Hello" << ", " << "Stream" << " " << "World!";
    std::cout << "String stream: " << ss.str() << std::endl;
}

// 13. Hello World with threading (C++11)
#include <thread>
#include <mutex>
#include <atomic>

std::mutex mtx;
std::atomic<int> counter(0);

void printHello(int id) {
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "Hello from thread " << id << "!" << std::endl;
    counter++;
}

void helloWithThreading() {
    std::vector<std::thread> threads;
    
    // Create multiple threads
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(printHello, i);
    }
    
    // Wait for all threads to complete
    for (auto& thread : threads) {
        thread.join();
    }
    
    std::cout << "Counter value: " << counter << std::endl;
}

// 14. Hello World with chrono (C++11)
void helloWithChrono() {
    // Get current time
    auto now = std::chrono::system_clock::now();
    auto now_time = std::chrono::system_clock::to_time_t(now);
    
    std::cout << "Current time: " << std::ctime(&now_time);
    
    // Measure execution time
    auto start = std::chrono::high_resolution_clock::now();
    
    // Simulate some work
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    
    std::cout << "Execution time: " << duration.count() << " milliseconds" << std::endl;
}

// Main function demonstrating all examples
int main() {
    std::cout << "=== C++ Hello World Examples ===" << std::endl;
    
    // Basic examples
    std::cout << "\n1. Basic Hello World:" << std::endl;
    std::cout << "Hello, World!" << std::endl;
    
    std::cout << "\n2. Variables and types:" << std::endl;
    helloWithVariables();
    
    std::cout << "\n3. Functions:" << std::endl;
    printMessage(sayHello());
    printMessage(greetUser("C++"));
    
    std::cout << "\n4. References and pointers:" << std::endl;
    helloWithReferences();
    
    std::cout << "\n5. Classes:" << std::endl;
    Greeter greeter1;
    greeter1.greet();
    
    Greeter greeter2("Welcome to C++");
    greeter2.greet("Programmer");
    
    std::cout << "\n6. Inheritance:" << std::endl;
    DerivedGreeter derived("Hello", "from derived class!");
    derived.greet();
    derived.specialGreet();
    
    std::cout << "\n7. Templates:" << std::endl;
    std::cout << "Template add (int): " << add(5, 3) << std::endl;
    std::cout << "Template add (double): " << add(5.5, 3.3) << std::endl;
    
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::cout << "Template vector: ";
    printVector(numbers);
    
    std::cout << "\n8. STL containers:" << std::endl;
    helloWithContainers();
    
    std::cout << "\n9. Smart pointers:" << std::endl;
    helloWithSmartPointers();
    
    std::cout << "\n10. Lambda expressions:" << std::endl;
    helloWithLambdas();
    
    std::cout << "\n11. Exception handling:" << std::endl;
    helloWithExceptions();
    
    std::cout << "\n12. File I/O:" << std::endl;
    helloWithFileIO();
    
    std::cout << "\n13. Threading:" << std::endl;
    helloWithThreading();
    
    std::cout << "\n14. Chrono:" << std::endl;
    helloWithChrono();
    
    std::cout << "\n=== All C++ Examples Completed ===" << std::endl;
    
    return 0;
}
代码cpp中等

C++ STL 算法

C++标准模板库算法和容器的综合示例

难度

8/10

预计时间

35 min

标签

cpp, c++, stl, algorithms

前置条件

Basic C++ syntax and templates

cpp
// C++ STL Algorithms Examples

#include <iostream>
#include <vector>
#include <list>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <random>
#include <chrono>

class STLAlgorithmsDemo {
public:
    static void demonstrateAlgorithms() {
        std::cout << "=== C++ STL Algorithms Demo ===" << std::endl;
        
        nonModifyingAlgorithms();
        modifyingAlgorithms();
        sortingAlgorithms();
        numericAlgorithms();
        containerAdaptors();
        advancedAlgorithms();
    }

private:
    // 1. Non-modifying Algorithms
    static void nonModifyingAlgorithms() {
        std::cout << "\n1. Non-modifying Algorithms:" << std::endl;
        
        std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        // std::find
        auto it = std::find(numbers.begin(), numbers.end(), 5);
        if (it != numbers.end()) {
            std::cout << "Found 5 at position: " << std::distance(numbers.begin(), it) << std::endl;
        }
        
        // std::find_if
        auto evenIt = std::find_if(numbers.begin(), numbers.end(), [](int n) { return n % 2 == 0; });
        if (evenIt != numbers.end()) {
            std::cout << "First even number: " << *evenIt << std::endl;
        }
        
        // std::count and std::count_if
        int countEvens = std::count_if(numbers.begin(), numbers.end(), [](int n) { return n % 2 == 0; });
        std::cout << "Count of even numbers: " << countEvens << std::endl;
        
        // std::for_each
        std::cout << "All numbers: ";
        std::for_each(numbers.begin(), numbers.end(), [](int n) {
            std::cout << n << " ";
        });
        std::cout << std::endl;
        
        // std::all_of, std::any_of, std::none_of
        bool allPositive = std::all_of(numbers.begin(), numbers.end(), [](int n) { return n > 0; });
        bool hasEven = std::any_of(numbers.begin(), numbers.end(), [](int n) { return n % 2 == 0; });
        bool noNegative = std::none_of(numbers.begin(), numbers.end(), [](int n) { return n < 0; });
        
        std::cout << "All positive: " << std::boolalpha << allPositive << std::endl;
        std::cout << "Has even: " << hasEven << std::endl;
        std::cout << "No negative: " << noNegative << std::endl;
        
        // std::equal
        std::vector<int> copy = numbers;
        bool equal = std::equal(numbers.begin(), numbers.end(), copy.begin());
        std::cout << "Vectors equal: " << equal << std::endl;
        
        // std::search
        std::vector<int> sub = {4, 5, 6};
        auto searchIt = std::search(numbers.begin(), numbers.end(), sub.begin(), sub.end());
        if (searchIt != numbers.end()) {
            std::cout << "Subsequence found at position: " << std::distance(numbers.begin(), searchIt) << std::endl;
        }
    }
    
    // 2. Modifying Algorithms
    static void modifyingAlgorithms() {
        std::cout << "\n2. Modifying Algorithms:" << std::endl;
        
        std::vector<int> numbers = {1, 2, 3, 4, 5};
        
        // std::copy
        std::vector<int> copy;
        std::copy(numbers.begin(), numbers.end(), std::back_inserter(copy));
        std::cout << "Copy: ";
        printContainer(copy);
        
        // std::transform
        std::vector<int> squared;
        std::transform(numbers.begin(), numbers.end(), std::back_inserter(squared),
                      [](int n) { return n * n; });
        std::cout << "Squared: ";
        printContainer(squared);
        
        // std::fill and std::fill_n
        std::vector<int> filled(5);
        std::fill(filled.begin(), filled.end(), 42);
        std::cout << "Filled with 42: ";
        printContainer(filled);
        
        // std::generate and std::generate_n
        std::vector<int> generated(5);
        int counter = 1;
        std::generate(generated.begin(), generated.end(), [&counter]() { return counter++; });
        std::cout << "Generated sequence: ";
        printContainer(generated);
        
        // std::replace and std::replace_if
        std::vector<int> replaceVec = {1, 2, 3, 2, 4, 2, 5};
        std::replace(replaceVec.begin(), replaceVec.end(), 2, 99);
        std::cout << "After replace 2 with 99: ";
        printContainer(replaceVec);
        
        // std::remove and std::remove_if
        std::vector<int> removeVec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        auto newEnd = std::remove_if(removeVec.begin(), removeVec.end(), [](int n) { return n % 2 == 0; });
        removeVec.erase(newEnd, removeVec.end());
        std::cout << "After removing evens: ";
        printContainer(removeVec);
        
        // std::unique
        std::vector<int> uniqueVec = {1, 2, 2, 3, 3, 3, 4, 5, 5};
        auto uniqueEnd = std::unique(uniqueVec.begin(), uniqueVec.end());
        uniqueVec.erase(uniqueEnd, uniqueVec.end());
        std::cout << "After removing duplicates: ";
        printContainer(uniqueVec);
        
        // std::reverse
        std::vector<int> reverseVec = {1, 2, 3, 4, 5};
        std::reverse(reverseVec.begin(), reverseVec.end());
        std::cout << "Reversed: ";
        printContainer(reverseVec);
        
        // std::rotate
        std::vector<int> rotateVec = {1, 2, 3, 4, 5};
        std::rotate(rotateVec.begin(), rotateVec.begin() + 2, rotateVec.end());
        std::cout << "Rotated left by 2: ";
        printContainer(rotateVec);
    }
    
    // 3. Sorting Algorithms
    static void sortingAlgorithms() {
        std::cout << "\n3. Sorting Algorithms:" << std::endl;
        
        std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 7, 4, 6};
        
        // std::sort
        std::vector<int> sorted = numbers;
        std::sort(sorted.begin(), sorted.end());
        std::cout << "Sorted ascending: ";
        printContainer(sorted);
        
        // std::sort with custom comparator
        std::vector<int> descending = numbers;
        std::sort(descending.begin(), descending.end(), std::greater<int>());
        std::cout << "Sorted descending: ";
        printContainer(descending);
        
        // std::stable_sort
        std::vector<std::pair<int, std::string>> pairs = {
            {2, "two"}, {1, "one"}, {2, "two again"}, {1, "one again"}
        };
        std::stable_sort(pairs.begin(), pairs.end());
        std::cout << "Stable sorted pairs:" << std::endl;
        for (const auto& p : pairs) {
            std::cout << "(" << p.first << ", " << p.second << ") ";
        }
        std::cout << std::endl;
        
        // std::partial_sort
        std::vector<int> partial = {5, 2, 8, 1, 9, 3, 7, 4, 6};
        std::partial_sort(partial.begin(), partial.begin() + 3, partial.end());
        std::cout << "Partial sort (first 3): ";
        printContainer(std::vector<int>(partial.begin(), partial.begin() + 3));
        
        // std::nth_element
        std::vector<int> nth = {5, 2, 8, 1, 9, 3, 7, 4, 6};
        std::nth_element(nth.begin(), nth.begin() + 4, nth.end());
        std::cout << "After nth_element (5th element is in correct position): ";
        printContainer(nth);
        
        // std::lower_bound and std::upper_bound
        std::vector<int> sortedVec = {1, 2, 2, 3, 4, 4, 4, 5, 6};
        auto lower = std::lower_bound(sortedVec.begin(), sortedVec.end(), 4);
        auto upper = std::upper_bound(sortedVec.begin(), sortedVec.end(), 4);
        
        std::cout << "Lower bound for 4: " << std::distance(sortedVec.begin(), lower) << std::endl;
        std::cout << "Upper bound for 4: " << std::distance(sortedVec.begin(), upper) << std::endl;
        
        // std::binary_search
        bool found = std::binary_search(sortedVec.begin(), sortedVec.end(), 4);
        std::cout << "Binary search for 4: " << std::boolalpha << found << std::endl;
        
        // std::merge
        std::vector<int> vec1 = {1, 3, 5, 7};
        std::vector<int> vec2 = {2, 4, 6, 8};
        std::vector<int> merged;
        std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(merged));
        std::cout << "Merged: ";
        printContainer(merged);
    }
    
    // 4. Numeric Algorithms
    static void numericAlgorithms() {
        std::cout << "\n4. Numeric Algorithms:" << std::endl;
        
        std::vector<int> numbers = {1, 2, 3, 4, 5};
        
        // std::accumulate
        int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
        std::cout << "Sum: " << sum << std::endl;
        
        // std::accumulate with custom operation
        int product = std::accumulate(numbers.begin(), numbers.end(), 1, std::multiplies<int>());
        std::cout << "Product: " << product << std::endl;
        
        // std::inner_product
        std::vector<int> vec1 = {1, 2, 3};
        std::vector<int> vec2 = {4, 5, 6};
        int innerProduct = std::inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0);
        std::cout << "Inner product: " << innerProduct << std::endl;
        
        // std::partial_sum
        std::vector<int> partialSums;
        std::partial_sum(numbers.begin(), numbers.end(), std::back_inserter(partialSums));
        std::cout << "Partial sums: ";
        printContainer(partialSums);
        
        // std::adjacent_difference
        std::vector<int> adjacentDiff;
        std::adjacent_difference(numbers.begin(), numbers.end(), std::back_inserter(adjacentDiff));
        std::cout << "Adjacent differences: ";
        printContainer(adjacentDiff);
        
        // std::iota
        std::vector<int> iotaVec(10);
        std::iota(iotaVec.begin(), iotaVec.end(), 1);
        std::cout << "Iota (1 to 10): ";
        printContainer(iotaVec);
    }
    
    // 5. Container Adaptors
    static void containerAdaptors() {
        std::cout << "\n5. Container Adaptors:" << std::endl;
        
        // Stack
        std::stack<int> stack;
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        std::cout << "Stack: ";
        while (!stack.empty()) {
            std::cout << stack.top() << " ";
            stack.pop();
        }
        std::cout << std::endl;
        
        // Queue
        std::queue<int> queue;
        queue.push(1);
        queue.push(2);
        queue.push(3);
        
        std::cout << "Queue: ";
        while (!queue.empty()) {
            std::cout << queue.front() << " ";
            queue.pop();
        }
        std::cout << std::endl;
        
        // Priority Queue
        std::priority_queue<int> pq;
        pq.push(3);
        pq.push(1);
        pq.push(4);
        pq.push(2);
        
        std::cout << "Priority Queue: ";
        while (!pq.empty()) {
            std::cout << pq.top() << " ";
            pq.pop();
        }
        std::cout << std::endl;
        
        // Priority Queue with custom comparator
        std::priority_queue<int, std::vector<int>, std::greater<int>> minPq;
        minPq.push(3);
        minPq.push(1);
        minPq.push(4);
        minPq.push(2);
        
        std::cout << "Min Priority Queue: ";
        while (!minPq.empty()) {
            std::cout << minPq.top() << " ";
            minPq.pop();
        }
        std::cout << std::endl;
    }
    
    // 6. Advanced Algorithms
    static void advancedAlgorithms() {
        std::cout << "\n6. Advanced Algorithms:" << std::endl;
        
        // std::shuffle
        std::vector<int> shuffleVec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        std::random_device rd;
        std::mt19937 g(rd());
        std::shuffle(shuffleVec.begin(), shuffleVec.end(), g);
        std::cout << "Shuffled: ";
        printContainer(shuffleVec);
        
        // std::sample (C++17)
        std::vector<int> population = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        std::vector<int> sample;
        std::sample(population.begin(), population.end(), std::back_inserter(sample), 3, g);
        std::cout << "Random sample of 3: ";
        printContainer(sample);
        
        // std::min_element and std::max_element
        std::vector<int> minMaxVec = {5, 2, 8, 1, 9, 3};
        auto minIt = std::min_element(minMaxVec.begin(), minMaxVec.end());
        auto maxIt = std::max_element(minMaxVec.begin(), minMaxVec.end());
        
        std::cout << "Min element: " << *minIt << " at position " << std::distance(minMaxVec.begin(), minIt) << std::endl;
        std::cout << "Max element: " << *maxIt << " at position " << std::distance(minMaxVec.begin(), maxIt) << std::endl;
        
        // std::minmax_element
        auto minMaxPair = std::minmax_element(minMaxVec.begin(), minMaxVec.end());
        std::cout << "Min and max together: " << *minMaxPair.first << " and " << *minMaxPair.second << std::endl;
        
        // std::clamp (C++17)
        int value = 15;
        int clamped = std::clamp(value, 10, 20);
        std::cout << "Clamped value (15 between 10-20): " << clamped << std::endl;
        
        // std::gcd and std::lcm (C++17)
        int a = 12, b = 18;
        std::cout << "GCD of " << a << " and " << b << ": " << std::gcd(a, b) << std::endl;
        std::cout << "LCM of " << a << " and " << b << ": " << std::lcm(a, b) << std::endl;
        
        // std::partition and std::stable_partition
        std::vector<int> partitionVec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        auto partitionIt = std::partition(partitionVec.begin(), partitionVec.end(), [](int n) { return n % 2 == 0; });
        
        std::cout << "Partitioned (evens first): ";
        printContainer(partitionVec);
        
        // std::set operations
        std::vector<int> setA = {1, 2, 3, 4, 5};
        std::vector<int> setB = {4, 5, 6, 7, 8};
        std::vector<int> result;
        
        // Set union
        std::set_union(setA.begin(), setA.end(), setB.begin(), setB.end(), std::back_inserter(result));
        std::cout << "Set union: ";
        printContainer(result);
        
        result.clear();
        // Set intersection
        std::set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(), std::back_inserter(result));
        std::cout << "Set intersection: ";
        printContainer(result);
        
        result.clear();
        // Set difference
        std::set_difference(setA.begin(), setA.end(), setB.begin(), setB.end(), std::back_inserter(result));
        std::cout << "Set difference (A - B): ";
        printContainer(result);
        
        // std::move and std::move_backward
        std::vector<int> moveSrc = {1, 2, 3, 4, 5};
        std::vector<int> moveDest(5);
        std::move(moveSrc.begin(), moveSrc.end(), moveDest.begin());
        std::cout << "After std::move - Destination: ";
        printContainer(moveDest);
    }
    
    // Helper function to print containers
    template<typename T>
    static void printContainer(const T& container) {
        for (const auto& item : container) {
            std::cout << item << " ";
        }
        std::cout << std::endl;
    }
};

// Hash function examples
class HashExamples {
public:
    static void demonstrateHashFunctions() {
        std::cout << "\n=== Hash Function Examples ===" << std::endl;
        
        // std::hash
        std::hash<std::string> stringHash;
        std::hash<int> intHash;
        
        std::string text = "Hello, World!";
        int number = 42;
        
        std::cout << "Hash of '" << text << "': " << stringHash(text) << std::endl;
        std::cout << "Hash of " << number << ": " << intHash(number) << std::endl;
        
        // Using unordered containers
        std::unordered_map<std::string, int> wordCounts = {
            {"hello", 2},
            {"world", 1},
            {"cpp", 3}
        };
        
        std::cout << "Unordered map:" << std::endl;
        for (const auto& pair : wordCounts) {
            std::cout << pair.first << ": " << pair.second << std::endl;
        }
        
        std::unordered_set<std::string> uniqueWords = {"hello", "world", "cpp", "hello"};
        std::cout << "Unordered set: ";
        for (const auto& word : uniqueWords) {
            std::cout << word << " ";
        }
        std::cout << std::endl;
    }
};

int main() {
    STLAlgorithmsDemo::demonstrateAlgorithms();
    HashExamples::demonstrateHashFunctions();
    
    std::cout << "\n=== All STL Algorithm Examples Completed ===" << std::endl;
    
    return 0;
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

容器发布前的 Dockerfile 与环境配置审查

检查 Dockerfile 规则、镜像引用格式与环境变量重复键,解释预发布和生产配置差异,形成可核对的容器发布记录。

专题

域名上线前的 DNS、DNSSEC 与 HTTPS 验收

先拟定 DNS 区域记录,再核对在线解析、DNSSEC 委派和实际提供的 HTTPS 证书,为域名上线留下可复核的依据。

专题

重复日历与 ICS 日程安排

跨时区规划并验证重复会议,处理工作日、节假日、冲突和 ICS 导出要求。

专题

API Mock 夹具生成与审阅

生成可重复的 Mock 负载,构造符合格式的边界值,发现易混淆字段名,并在共享临时 Mock 服务前完成复核。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们
编程语言

Go 示例

Go (Golang) 代码示例和Hello World演示

编程语言

Java 示例

Java代码示例和Hello World演示

编程语言

JavaScript 示例

JavaScript代码示例和Hello World演示

编程语言

Python 示例

Python代码示例和Hello World演示

编程语言

TypeScript 示例

TypeScript代码示例,包含类型安全和Hello World演示

编程语言

Zig 示例

Zig编程语言示例 - 简单、高效的系统编程,具有内存安全性