algorithm


Header: <algorithm>

The <algorithm> header is a fundamental part of the C++ Standard Library. It provides a collection of functions designed to perform algorithmic operations on ranges of elements. These algorithms are highly optimized and can significantly simplify common programming tasks, making your code more efficient and readable.

Key Characteristics

Example 1: Basic Sorting

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

int main() {
    std::vector<int> numbers = {5, 2, 8, 1, 9, 3};

    std::sort(numbers.begin(), numbers.end());

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

Example 2: Finding Elements

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

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

    auto it = std::find(numbers.begin(), numbers.end(), 7);

    if (it != numbers.end()) {
        std::cout << "Found 7 at position: " << std::distance(numbers.begin(), it) << std::endl;
    } else {
        std::cout << "7 not found in the vector" << std::endl;
    }

    return 0;
}

Explanation

Example 3: Transforming Elements

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

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    std::vector<int> squared(numbers.size());

    std::transform(numbers.begin(), numbers.end(), squared.begin(),
                   [](int x) { return x * x; });

    for (int num : squared) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

Example 4: Removing Elements

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

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

    numbers.erase(std::remove_if(numbers.begin(), numbers.end(),
                                 [](int x) { return x % 2 == 0; }),
                  numbers.end());

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

Additional Considerations

Summary

The <algorithm> header is a powerful tool in the C++ Standard Library that provides a wide range of algorithms for working with containers and ranges of elements. It includes functions for sorting, searching, modifying, and transforming data, among many others. By leveraging these algorithms, developers can write more concise, efficient, and readable code.

The examples provided demonstrate some common use cases:

  1. Basic sorting of a vector
  2. Finding an element in a container
  3. Transforming elements using a lambda function
  4. Removing elements that satisfy a certain condition

These examples showcase the versatility and ease of use of the algorithms provided by <algorithm>. By mastering these algorithms, C++ developers can significantly improve their productivity and code quality.

Previous Page | Course Schedule | Course Content