For example, I have a vector as v=[7,4,5,10,13]. Here my target number is 6. I am first sorting the vector as
sort(v.begin(), v.end());
Now my output would be [4,5,7,10,13]. After which I want to print the numbers greater than or equal to '6' which will give me output as [7,10,13].
Please suggest a suitable way in cpp to perform this task.
CodePudding user response:
Use std::upper_bound:
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> v = {7,4,5,10,13};
std::sort(v.begin(), v.end());
auto iter = std::upper_bound(v.begin(), v.end(), 6);
for (; iter != v.end(); iter)
std::cout << *iter << " ";
}
Output:
7 10 13
CodePudding user response:
This is my quick solution
std::vector<int> v = {7,4,5,10,13};
std::sort(v.begin(), v.end());
std::copy_if(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "),
[](int a){ return a > 6;})
CodePudding user response:
Or if you compiler already supports it use
#include <algorithm>
#include <ranges>
#include <vector>
#include <iostream>
auto larger_then_6 = [](int i) { return i > 6; };
int main()
{
std::vector<int> v = { 7,4,5,10,13 };
std::sort(v.begin(), v.end());
for (auto value : v | std::views::filter(larger_then_6))
{
std::cout << value << " ";
}
std::cout << std::endl;
}