Modern C++ STL Algorithms and Container Manipulation

String and Vector Reversal/Rotation

The C++ Standard Template Library provides versatile algorithms for manipulating sequence iterators. The std::reverse and std::reverse_copy algorithms invert element orders, while std::rotate shifts elements within a given range, effectively creating circular permutations.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

template<typename Container>
void display(const Container& c) {
    for (const auto& item : c) std::cout << item << " ";
    std::cout << "\n";
}

void demonstrate_string_ops() {
    std::string original = "abcdefg";
    std::cout << "Original string: " << original << "\n";
    
    std::string reversed = original;
    std::reverse(reversed.begin(), reversed.end());
    std::cout << "Reversed string: " << reversed << "\n";
    
    std::string target(original.size(), ' '); 
    std::reverse_copy(original.begin(), original.end(), target.begin());
    std::cout << "Reverse copied string: " << target << "\n";
}

void demonstrate_vector_ops() {
    std::vector<int> sequence = {10, 20, 30, 40, 50, 60, 70};
    std::cout << "Original vector: ";
    display(sequence);

    std::vector<int> left_shifted = sequence;
    std::rotate(left_shifted.begin(), left_shifted.begin() + 2, left_shifted.end());
    std::cout << "Left shifted by 2: ";
    display(left_shifted);

    std::vector<int> right_shifted = sequence;
    std::rotate(right_shifted.begin(), right_shifted.end() - 1, right_shifted.end());
    std::cout << "Right shifted by 1: ";
    display(right_shifted);
}

int main() {
    demonstrate_string_ops();
    demonstrate_vector_ops();
    return 0;
}

Random Generation and Statistical Analysis

Using std::generate alongside a modern random number engine populates containers efficiently. Statistical properties like minimum, maximum, and average values can be extracted using std::minmax_element and std::accumulate. By sorting the dataset, trimmed means that exclude outliers are straightforward to compute.

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <random>
#include <iomanip>

template<typename Seq>
void print_seq(const Seq& s) {
    for (auto val : s) std::cout << val << " ";
    std::cout << "\n";
}

int main() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dist(1, 50);

    std::vector<int> nums(8);
    std::generate(nums.begin(), nums.end(), [&]() { return dist(gen); });
    
    std::cout << "Random values: ";
    print_seq(nums);

    auto [min_it, max_it] = std::minmax_element(nums.begin(), nums.end());
    std::cout << "Min: " << *min_it << ", Max: " << *max_it << "\n";

    double mean = std::accumulate(nums.begin(), nums.end(), 0.0) / nums.size();
    std::cout << "Mean: " << std::fixed << std::setprecision(2) << mean << "\n";

    std::vector<int> sorted_nums = nums;
    std::sort(sorted_nums.begin(), sorted_nums.end());
    
    double trimmed_mean = std::accumulate(sorted_nums.begin() + 1, sorted_nums.end() - 1, 0.0) / (sorted_nums.size() - 2);
    std::cout << "Trimmed mean (excluding extremes): " << trimmed_mean << "\n";

    return 0;
}

String Symmetry Verification

A palindrome checker can be implemented by comparing characters from opposite ends of the string moving towards the center. This two-pointer approach avoids allocating a reversed copy of the string, offering better memory efficiency.

#include <iostream>
#include <string>

bool check_symmetry(const std::string& text) {
    int left = 0;
    int right = text.length() - 1;
    while (left < right) {
        if (text[left] != text[right]) return false;
        left++;
        right--;
    }
    return true;
}

int main() {
    std::string input;
    while (std::cin >> input) {
        std::cout << std::boolalpha << check_symmetry(input) << "\n";
    }
    return 0;
}

Base-N Integer Conversion

Converting a decimal integer to other bases involves repeatedly dividing the number by the target base and recording the remainders. Mapping remainders greater than 9 to alphabetic characters (A-F) handles hexadecimal outputs. Since the remainders are generated in reverse order, std::reverse corrects the sequence before returning the result.

#include <iostream>
#include <string>
#include <algorithm>

std::string convert_base(int value, int base = 2) {
    if (value == 0) return "0";
    const char digits[] = "0123456789ABCDEF";
    std::string result;
    int remaining = value;
    while (remaining > 0) {
        result += digits[remaining % base];
        remaining /= base;
    }
    std::reverse(result.begin(), result.end());
    return result;
}

int main() {
    int val;
    while (std::cin >> val) {
        std::cout << "Decimal: " << val << "\n";
        std::cout << "Binary: " << convert_base(val) << "\n";
        std::cout << "Octal: " << convert_base(val, 8) << "\n";
        std::cout << "Hexadecimal: " << convert_base(val, 16) << "\n\n";
    }
    return 0;
}

Alphabet Shift Table Generation

Combining ASCII manipulation with std::rotate constructs a Vigenère-like cipher table. The lowercase alphabet serves as the header, while an uppercase copy is iteratively rotated to display each shift permutation.

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>

int main() {
    const int ALPHABET_SIZE = 26;
    std::vector<char> alphabet;
    for (char c = 'a'; c <= 'z'; ++c) alphabet.push_back(c);

    std::cout << std::setw(3) << " ";
    for (char c : alphabet) std::cout << std::setw(3) << c;
    std::cout << "\n";

    std::vector<char> shifted_row = alphabet;
    for (char& c : shifted_row) c -= 32; // Convert to uppercase

    for (int shift = 1; shift <= ALPHABET_SIZE; ++shift) {
        std::rotate(shifted_row.begin(), shifted_row.begin() + 1, shifted_row.end());
        std::cout << std::setw(3) << shift;
        for (char c : shifted_row) std::cout << std::setw(3) << c;
        std::cout << "\n";
    }
    return 0;
}

Arithmetic Quiz Engine

An interactive quiz system can randomly generate elementary arithmetic problems. By encapsulating the logic within a class, constraints such as non-negative subtraction results and exact integer division are enforced through a regeneration loop. The engine tracks user responses and calculates the final accuracy percentage.

#include <iostream>
#include <iomanip>
#include <random>

class MathProblem {
private:
    int operand_a, operand_b;
    char operation;
    std::mt19937 rng;
    std::uniform_int_distribution<int> num_dist;
    std::uniform_int_distribution<int> op_dist;

public:
    MathProblem() : rng(std::random_device{}()), num_dist(1, 10), op_dist(0, 3) {}

    void create_valid_problem() {
        while (true) {
            operand_a = num_dist(rng);
            operand_b = num_dist(rng);
            int op_idx = op_dist(rng);
            
            if (op_idx == 0) { operation = '+'; return; }
            if (op_idx == 1 && operand_a >= operand_b) { operation = '-'; return; }
            if (op_idx == 2) { operation = '*'; return; }
            if (op_idx == 3 && operand_b != 0 && operand_a % operand_b == 0) { operation = '/'; return; }
        }
    }

    void prompt_user() {
        create_valid_problem();
        std::cout << operand_a << " " << operation << " " << operand_b << " = ";
    }

    bool verify(int answer) const {
        switch (operation) {
            case '+': return answer == operand_a + operand_b;
            case '-': return answer == operand_a - operand_b;
            case '*': return answer == operand_a * operand_b;
            case '/': return answer == operand_a / operand_b;
        }
        return false;
    }
};

int main() {
    const int TOTAL_QUESTIONS = 10;
    MathProblem problem;
    int user_answer, correct_count = 0;

    for (int i = 0; i < TOTAL_QUESTIONS; ++i) {
        problem.prompt_user();
        std::cin >> user_answer;
        if (problem.verify(user_answer)) correct_count++;
    }

    double accuracy = static_cast<double>(correct_count) / TOTAL_QUESTIONS * 100;
    std::cout << std::fixed << std::setprecision(2) << "Accuracy: " << accuracy << "%\n";
    return 0;
}

Tags: C++ STL algorithms containers modern C++

Posted on Fri, 26 Jun 2026 16:42:00 +0000 by CooKies37