Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C++ Standard Algorithm Implementations for Data Manipulation

Tech 1

String and Vector Reversal with Standard Algorithms

Reverse Operations

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

template<typename Container>
void display(const Container& data);

void reverse_string_example();
void reverse_vector_example();
void rotate_vector_example();

int main() {
    reverse_string_example();
    reverse_vector_example();
    rotate_vector_example();
}

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

void reverse_string_example() {
    std::string original{"programming"};
    std::cout << "Original: " << original << std::endl;
    
    std::string reversed_inplace{original};
    std::reverse(reversed_inplace.begin(), reversed_inplace.end());
    std::cout << "In-place reversed: " << reversed_inplace << std::endl;
    
    std::string reversed_copy(original.size(), ' ');
    std::reverse_copy(original.begin(), original.end(), reversed_copy.begin());
    std::cout << "Copy reversed: " << reversed_copy << std::endl;
}

void reverse_vector_example() {
    std::vector<int> numbers{1, 3, 5, 7, 9};
    std::cout << "Original vector: ";
    display(numbers);
    
    std::vector<int> reversed_numbers{numbers};
    std::reverse(reversed_numbers.begin(), reversed_numbers.end());
    std::cout << "Reversed vector: ";
    display(reversed_numbers);
}

void rotate_vector_example() {
    std::vector<int> sequence{1, 2, 3, 4, 5, 6};
    std::cout << "Initial sequence: ";
    display(sequence);
    
    std::vector<int> left_rotate{sequence};
    std::rotate(left_rotate.begin(), left_rotate.begin() + 2, left_rotate.end());
    std::cout << "Left rotated by 2: ";
    display(left_rotate);
    
    std::vector<int> right_rotate{sequence};
    std::rotate(right_rotate.begin(), right_rotate.end() - 3, right_rotate.end());
    std::cout << "Right rotated by 3: ";
    display(right_rotate);
}

Key Differences: reverse modifies the original container, while reverse_copy preserves the original and stores the result in a different location.

Container Operations with Generate and Sort Algorithms

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

template<typename T>
void print_container(const T& container);
int random_generator();
void container_operations();

int main() {
    std::srand(std::time(nullptr));
    container_operations();
}

template<typename T>
void print_container(const T& container) {
    for(const auto& element : container)
        std::cout << element << ' ';
    std::cout << '\n';
}

int random_generator() {
    return std::rand() % 100 + 1;
}

void container_operations() {
    std::vector<int> data(8);
    std::generate(data.begin(), data.end(), random_generator);
    std::cout << "Generated data: ";
    print_container(data);
    
    std::vector<int> sorted_data{data};
    std::sort(sorted_data.begin(), sorted_data.end());
    std::cout << "Fully sorted: ";
    print_container(sorted_data);
    
    auto [min_iter, max_iter] = std::minmax_element(data.begin(), data.end());
    std::cout << "Min: " << *min_iter << ", Max: " << *max_iter << std::endl;
    
    double average = std::accumulate(data.begin(), data.end(), 0.0) / data.size();
    std::cout << "Average: " << average << std::endl;
}

Algorithm Efficiency: minmax_element finds both minimum and maximum elements in a single pass through the container.

Character Transformation and Case Conversion

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

unsigned char character_shift(unsigned char ch);
void case_conversion_demo();
void character_transformation_demo();

int main() {
    case_conversion_demo();
    character_transformation_demo();
}

unsigned char character_shift(unsigned char ch) {
    if(ch == 'z') return 'a';
    if(ch == 'Z') return 'A';
    if(std::isalpha(ch)) return ch + 1;
    return ch;
}

void case_conversion_demo() {
    std::string text{"Algorithm Design"};
    std::string lower_text;
    std::string upper_text;
    
    for(char ch : text) {
        lower_text += std::tolower(ch);
        upper_text += std::toupper(ch);
    }
    
    std::cout << "Original: " << text << std::endl;
    std::cout << "Lowercase: " << lower_text << std::endl;
    std::cout << "Uppercase: " << upper_text << std::endl;
}

void character_transformation_demo() {
    std::string input{"hello world"};
    std::string output(input.size(), ' ');
    
    std::transform(input.begin(), input.end(), output.begin(), character_shift);
    std::cout << "Transformed: " << output << std::endl;
}

Transform Parameters: Input range, output iterator, and transformation function. Using the same iterator for input and output modifies the original data.

Palindrome Detection with Case Handling

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

bool check_palindrome(const std::string& str);
bool check_palindrome_ignore_case(const std::string& str);

int main() {
    std::string input;
    while(std::getline(std::cin, input)) {
        std::cout << "Case sensitive: " << std::boolalpha 
                  << check_palindrome(input) << std::endl;
        std::cout << "Case insensitive: " 
                  << check_palindrome_ignore_case(input) << std::endl;
    }
}

bool check_palindrome(const std::string& str) {
    return std::equal(str.begin(), str.begin() + str.size()/2, str.rbegin());
}

bool check_palindrome_ignore_case(const std::string& str) {
    std::string processed;
    std::transform(str.begin(), str.end(), std::back_inserter(processed), ::tolower);
    return std::equal(processed.begin(), processed.begin() + processed.size()/2, 
                     processed.rbegin());
}

Input Handling: Use std::getline instead of cin >> to process strings containing spaces.

Base Convertion Algorithm

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

std::string convert_base(int number, int base = 2);

int main() {
    int value;
    while(std::cin >> value) {
        std::cout << "Decimal: " << value << std::endl;
        std::cout << "Binary: " << convert_base(value) << std::endl;
        std::cout << "Octal: " << convert_base(value, 8) << std::endl;
        std::cout << "Hexadecimal: " << convert_base(value, 16) << std::endl;
    }
}

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

Alphabet Shifting Pattern Generation

#include <iostream>
#include <string>

int main() {
    const std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
    
    for(int shift = 0; shift < 26; ++shift) {
        std::string shifted = alphabet.substr(shift) + alphabet.substr(0, shift);
        
        for(char& ch : shifted) {
            ch = std::toupper(ch);
        }
        
        std::cout << shift + 1 << shifted << std::endl;
    }
    
    return 0;
}

Arithmetic Quiz Application

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>

int main() {
    std::srand(std::time(nullptr));
    const int question_count = 10;
    int correct_answers = 0;
    
    for(int i = 1; i <= question_count; ++i) {
        int operand1 = std::rand() % 10 + 1;
        int operand2 = std::rand() % 10 + 1;
        
        int operation = std::rand() % 4;
        char operator_symbol;
        int correct_result;
        
        switch(operation) {
            case 0:
                operator_symbol = '+';
                correct_result = operand1 + operand2;
                break;
            case 1:
                operator_symbol = '-';
                if(operand1 < operand2) std::swap(operand1, operand2);
                correct_result = operand1 - operand2;
                break;
            case 2:
                operator_symbol = '*';
                correct_result = operand1 * operand2;
                break;
            case 3:
                operator_symbol = '/';
                while(operand1 % operand2 != 0) {
                    operand2 = std::rand() % 10 + 1;
                }
                correct_result = operand1 / operand2;
                break;
        }
        
        std::cout << "Question " << i << ": " << operand1 << " " 
                  << operator_symbol << " " << operand2 << " = ";
        
        int user_answer;
        std::cin >> user_answer;
        
        if(user_answer == correct_result) {
            ++correct_answers;
        }
    }
    
    double accuracy = (static_cast<double>(correct_answers) / question_count) * 100;
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Accuracy: " << accuracy << "%" << std::endl;
    
    return 0;
}
Tags: C++

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.