C++ Reference

Strings

#include <iostream>
#include <string>
#include <algorithm> // For transform, sort, etc.
#include <cctype>    // For toupper, tolower
#include <vector>    // For splitting into a list of characters

int main() {
    std::string my_string = "Hello World";

    // Convert to uppercase
    std::transform(my_string.begin(), my_string.end(), my_string.begin(), ::toupper);
    std::cout << "Uppercase: " << my_string << std::endl;

    // Convert to lowercase
    std::transform(my_string.begin(), my_string.end(), my_string.begin(), ::tolower);
    std::cout << "Lowercase: " << my_string << std::endl;

    // Check if all characters are alphabetic
    bool is_alpha = std::all_of(my_string.begin(), my_string.end(), ::isalpha);
    std::cout << "Is alphabetic: " << is_alpha << std::endl;

    // Check if string is alphanumeric
    bool is_alnum = std::all_of(my_string.begin(), my_string.end(), ::isalnum);
    std::cout << "Is alphanumeric: " << is_alnum << std::endl;

    // ASCII value of the first character
    int ascii_value = static_cast<int>(my_string[0]);
    std::cout << "ASCII value of first character: " << ascii_value << std::endl;

    // Reverse the string
    std::reverse(my_string.begin(), my_string.end());
    std::cout << "Reversed: " << my_string << std::endl;

    // Split string into a list of characters
    std::vector<char> char_list(my_string.begin(), my_string.end());
    std::cout << "Split into characters: ";
    for (char c : char_list) std::cout << c << " ";
    std::cout << std::endl;

    // Check if a string contains a substring
    std::string substring = "World";
    if (my_string.find(substring) != std::string::npos) {
        std::cout << "Substring found!" << std::endl;
    }

    // Split a string based on a delimiter (space in this case)
    std::string str = "This is a test";
    std::vector<std::string> words;
    size_t pos = 0;
    std::string delimiter = " ";
    while ((pos = str.find(delimiter)) != std::string::npos) {
        words.push_back(str.substr(0, pos));
        str.erase(0, pos + delimiter.length());
    }
    words.push_back(str); // Add the last word

    std::cout << "Split based on spaces: ";
    for (const auto& word : words) std::cout << word << " ";
    std::cout << std::endl;

    // Replace a substring
    std::string my_string2 = "Hello World";
    std::string old_substring = "World";
    std::string new_substring = "C++";
    size_t start_pos = my_string2.find(old_substring);
    if (start_pos != std::string::npos) {
        my_string2.replace(start_pos, old_substring.length(), new_substring);
    }
    std::cout << "After replacement: " << my_string2 << std::endl;

    // Get index of a character
    char search_char = 'l';
    size_t index = my_string2.find(search_char);
    if (index != std::string::npos) {
        std::cout << "Character '" << search_char << "' found at index: " << index << std::endl;
    }

    // Sort a string (lexicographically)
    std::string my_str = "hello";
    std::string sorted_str = my_str;
    std::sort(sorted_str.begin(), sorted_str.end());
    std::cout << "Sorted string: " << sorted_str << std::endl;

    // Get sorted list of characters
    std::vector<char> sorted_char_list(my_str.begin(), my_str.end());
    std::sort(sorted_char_list.begin(), sorted_char_list.end());
    std::cout << "Sorted list of characters: ";
    for (char c : sorted_char_list) std::cout << c << " ";
    std::cout << std::endl;

    return 0;
}

Vectors

#include <vector>
#include <algorithm> // For sort, min, max, etc.
#include <numeric>   // For accumulate
#include <iostream>  // For input/output
#include <iterator>  // For iterators

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

    // Add elements to vector
    vec.push_back(6);       // Adds element to the end
    vec.pop_back();          // Removes the last element

    // Access elements
    int first = vec.front(); // First element
    int last = vec.back();   // Last element
    int atIndex = vec.at(2); // Access by index with bounds checking

    // Enumerate using index (manual)
    for (size_t i = 0; i < vec.size(); ++i) {
        std::cout << "Index " << i << ": " << vec[i] << std::endl;
    }

    // Enumerate using iterators
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << std::endl;
    }

    // Sort the vector (ascending or descending)
    std::sort(vec.begin(), vec.end());             // Ascending
    std::sort(vec.begin(), vec.end(), std::greater<>()); // Descending

    // Subtract indices of two vectors (similar to Python zip)
    std::vector<int> result;
    std::transform(vec.begin(), vec.end(), vec2.begin(), std::back_inserter(result),
                   [](int a, int b) { return b - a; });
    
    // Slicing (manually with iterators)
    std::vector<int> subvector(vec.begin() + 1, vec.begin() + 3); // Slicing vec[1:3]

    // Reverse the vector
    std::reverse(vec.begin(), vec.end());

    // Get a copy of the vector
    std::vector<int> copy = vec; // Copy of vector

    // Find min and max in a vector
    int min_value = *std::min_element(vec.begin(), vec.end());
    int max_value = *std::max_element(vec.begin(), vec.end());

    // Find an element in a vector
    auto it = std::find(vec.begin(), vec.end(), 3);
    if (it != vec.end()) {
        std::cout << "Element found at index " << std::distance(vec.begin(), it) << std::endl;
    }

    // Sum of elements in a vector
    int sum = std::accumulate(vec.begin(), vec.end(), 0);

    // Remove elements from a vector
    vec.erase(vec.begin() + 1);  // Remove element at index 1
    vec.erase(std::remove(vec.begin(), vec.end(), 3), vec.end()); // Remove all occurrences of 3

    // Clear the vector
    vec.clear();

    return 0;
}

Maps

#include <iostream>
#include <map>            // For std::map
#include <unordered_map>  // For std::unordered_map
#include <algorithm>      // For std::equal

int main() {
    // Initialize a map
    std::map<std::string, int> my_map = {{"apple", 1}, {"banana", 2}, {"orange", 3}};

    // Remove all elements
    my_map.clear();

    // Try to pop or return a specified default
    std::string key_to_pop = "apple";
    auto it = my_map.find(key_to_pop);
    int value = (it != my_map.end()) ? it->second : -1; // Default value is -1 if key not found
    if (it != my_map.end()) {
        my_map.erase(it);  // Remove the key-value pair
    }
    std::cout << "Popped value: " << value << std::endl;

    // Pop last key-item pair
    if (!my_map.empty()) {
        auto last_it = --my_map.end();  // Get iterator to the last element
        std::cout << "Popped last key-value pair: " << last_it->first << " -> " << last_it->second << std::endl;
        my_map.erase(last_it);  // Erase the last element
    }

    // Copy elements
    std::map<std::string, int> other_map = my_map; // Copy the map

    // Copy elements from keys
    std::map<std::string, int> from_keys_map;
    std::vector<std::string> keys = {"apple", "banana", "cherry"};
    for (const auto& key : keys) {
        from_keys_map[key] = 0; // Default value
    }

    // Get elements
    std::string key = "banana";
    int retrieved_value = (my_map.find(key) != my_map.end()) ? my_map[key] : -1;  // Default value is -1 if key not found
    std::cout << "Retrieved value: " << retrieved_value << std::endl;

    // Insert an element if key is not present
    std::string new_key = "pear";
    my_map.insert({new_key, 5});  // Will not insert if key already exists

    // Get all key-value pairs
    for (const auto& pair : my_map) {
        std::cout << pair.first << " -> " << pair.second << std::endl;
    }

    // Get all keys
    for (const auto& pair : my_map) {
        std::cout << "Key: " << pair.first << std::endl;
    }

    // Get all values
    for (const auto& pair : my_map) {
        std::cout << "Value: " << pair.second << std::endl;
    }

    // Update elements
    std::map<std::string, int> update_map = {{"cherry", 4}, {"banana", 7}};
    my_map.insert(update_map.begin(), update_map.end());  // Insert or update elements

    // Compare two maps
    std::map<std::string, int> my_map2 = {{"apple", 1}, {"banana", 2}};
    bool are_equal = (my_map == my_map2);
    std::cout << "Are maps equal? " << are_equal << std::endl;

    return 0;
}

Sets

#include <iostream>
#include <set>

int main() {
    // Create a set
    std::set<int> my_set;                // Empty set
    std::set<int> my_set2 = {1, 2, 3};   // Initialize with values

    // Set size
    std::cout << "Set size: " << my_set2.size() << std::endl;

    // Add elements
    my_set2.insert(4);  // Add an element to the set

    // Remove elements
    my_set2.erase(3);   // Remove an element (throws no error if item not found)

    // Discard (same as erase in C++ since it does not raise an error if the element is not found)
    my_set2.erase(2);   // Erase item if it exists, no error if it doesn't

    // Union of sets
    std::set<int> set1 = {1, 2, 3};
    std::set<int> set2 = {3, 4, 5};
    std::set<int> union_set;
    std::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), 
                   std::inserter(union_set, union_set.begin()));

    // Intersection of sets
    std::set<int> intersection_set;
    std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(),
                          std::inserter(intersection_set, intersection_set.begin()));

    // Difference of sets
    std::set<int> difference_set;
    std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(),
                        std::inserter(difference_set, difference_set.begin()));

    // Check if a set is a subset
    bool is_subset = std::includes(set2.begin(), set2.end(), set1.begin(), set1.end());
    std::cout << "Is set1 a subset of set2? " << is_subset << std::endl;

    // Check if a set is a superset (reverse of subset)
    bool is_superset = std::includes(set1.begin(), set1.end(), set2.begin(), set2.end());
    std::cout << "Is set1 a superset of set2? " << is_superset << std::endl;

    // Check if two sets are disjoint
    bool is_disjoint = std::none_of(set1.begin(), set1.end(), 
                                    [&](int elem){ return set2.find(elem) != set2.end(); });
    std::cout << "Are set1 and set2 disjoint? " << is_disjoint << std::endl;

    return 0;
}

Data Structures

#include <iostream>
#include <array>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <functional>  // For std::greater

int main() {
    // --- Array (Fixed size) ---
    std::array<int, 5> arr = {1, 2, 3, 4, 5};
    std::cout << "Array first element: " << arr[0] << std::endl;

    // --- Vector (Dynamic array) ---
    std::vector<int> vec = {1, 2, 3};
    vec.push_back(4);  // Add an element
    std::cout << "Vector last element: " << vec.back() << std::endl;

    // --- Deque (Double-ended queue) ---
    std::deque<int> deq = {1, 2, 3};
    deq.push_front(0);
    deq.push_back(4);
    std::cout << "Deque front: " << deq.front() << ", back: " << deq.back() << std::endl;

    // --- Queue (FIFO) ---
    std::queue<int> q;
    q.push(10);  q.push(20);
    std::cout << "Queue front: " << q.front() << std::endl;
    q.pop();

    // --- Stack (LIFO) ---
    std::stack<int> stack;
    stack.push(10); stack.push(20);
    std::cout << "Stack top: " << stack.top() << std::endl;
    stack.pop();

    // --- Priority Queue (Max Heap) ---
    std::priority_queue<int> max_heap;
    max_heap.push(10); max_heap.push(5); max_heap.push(30);
    std::cout << "Max Heap top: " << max_heap.top() << std::endl;

    // --- Priority Queue (Min Heap) ---
    std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;
    min_heap.push(10); min_heap.push(5); min_heap.push(30);
    std::cout << "Min Heap top: " << min_heap.top() << std::endl;

    // --- Set (Ordered set of unique elements) ---
    std::set<int> s = {3, 1, 4};
    s.insert(2);
    std::cout << "Set smallest element: " << *s.begin() << std::endl;

    // --- Unordered Set (Unordered unique elements) ---
    std::unordered_set<int> us = {3, 1, 4};
    us.insert(2);
    if (us.find(4) != us.end()) std::cout << "4 is in the unordered set" << std::endl;

    // --- Map (Ordered key-value pairs) ---
    std::map<std::string, int> my_map;
    my_map["apple"] = 10;  my_map["banana"] = 20;
    std::cout << "Map value for 'apple': " << my_map["apple"] << std::endl;

    // --- Unordered Map (Unordered key-value pairs) ---
    std::unordered_map<std::string, int> umap;
    umap["apple"] = 10;  umap["banana"] = 20;
    std::cout << "Unordered map value for 'apple': " << umap["apple"] << std::endl;

    return 0;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *