c++ remove numbers from vector if larger than n

C++ code to remove numbers from vector if larger than n:

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

int main() {
    std::vector<int> numbers = {1, 5, 10, 15, 20, 25};
    int n = 10;

    numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [n](int i) { return i > n; }), numbers.end());

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

    return 0;
}

Explanation for each step:

  1. Include necessary libraries:
  2. #include <iostream>: For input and output operations.
  3. #include <vector>: For using vectors.
  4. #include <algorithm>: For using algorithms like remove_if.

  5. Define the main function:

  6. The entry point of the program.

  7. Create a vector of numbers:

  8. std::vector<int> numbers = {1, 5, 10, 15, 20, 25};: Initializes a vector named numbers with some integer values.

  9. Set the threshold value:

  10. int n = 10;: Defines the threshold value n.

  11. Remove numbers larger than n from the vector:

  12. numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [n](int i) { return i > n; }), numbers.end());: Uses std::remove_if with a lambda function to remove elements from the vector that are greater than n.

  13. Output the modified vector:

  14. for (int num : numbers) { std::cout << num << " "; }: Prints the remaining numbers in the vector after removal.

  15. Return from the main function:

  16. return 0;: Indicates successful program execution.