例如,我有一个向量作为v=7,4,5,10,13。这里我的目标数是6。我首先用以下命令对向量进行排序:
sort(v.begin(), v.end());
现在我的输出应该是4,5,7,10,13。在此之后,我想打印大于或等于'6‘的数字,这将使我的输出为7,10,13。
在C++中,执行此任务的便捷方法是什么?
发布于 2021-09-20 06:14:40
#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 << " ";
}
输出:
7 10 13
发布于 2021-09-20 06:31:04
这是我的快速解决方案
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;})
发布于 2021-09-20 08:47:39
或者如果您的编译器已经支持它,请使用
#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;
}
https://stackoverflow.com/questions/69255822
复制