partition in STL using vector
Using the partition function in C++ STL with Vector
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::partition(numbers.begin(), numbers.end(), [](int x) { return x % 2 == 0; });
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
- Include Necessary Headers:
#include <iostream>
: Input/output stream.#include <algorithm>
: Standard template library algorithms.#include <vector>
: Vector container.Define Main Function:
Begin the main function.
Create Vector:
Define a vector called
numbers
and initialize it with some integer values.Use partition Function:
Call the
std::partition
function with the range of the vector and a lambda function as arguments. The lambda function returns true if the number is even.Output the Partitioned Vector:
Iterate through the vector and output the elements to the console.
Return from Main:
- End the main function and return 0.