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:
- Include necessary libraries:
#include <iostream>
: For input and output operations.#include <vector>
: For using vectors.#include <algorithm>
: For using algorithms likeremove_if
.Define the main function:
The entry point of the program.
Create a vector of numbers:
std::vector<int> numbers = {1, 5, 10, 15, 20, 25};
: Initializes a vector namednumbers
with some integer values.Set the threshold value:
int n = 10;
: Defines the threshold valuen
.Remove numbers larger than n from the vector:
numbers.erase(std::remove_if(numbers.begin(), numbers.end(), [n](int i) { return i > n; }), numbers.end());
: Usesstd::remove_if
with a lambda function to remove elements from the vector that are greater thann
.Output the modified vector:
for (int num : numbers) { std::cout << num << " "; }
: Prints the remaining numbers in the vector after removal.Return from the main function:
return 0;
: Indicates successful program execution.