在sort std :: vector中获取满足某些条件的范围(Get range in sorted std::vector satisfying to some condition)
我有一个排序的std::vector 。 现在我需要获得满足某些条件的项目范围。 例如
vector -> 1, 4, 25, 73 450 get range that is smaller then 100 -> {1, 4, 25, 73}我怎么能用std做到这一点?
I have a sorted std::vector. Now I need to get range of items that satisfy to some condition. E.g.
vector -> 1, 4, 25, 73 450 get range that is smaller then 100 -> {1, 4, 25, 73}How can I do this using std?
最满意答案
最简单的方法是使用标准算法std::lower_bound
例如
#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v = { 1, 4, 25, 73, 450 }; auto last = std::lower_bound( v.begin(), v.end(), 100 ); for ( auto it = v.begin(); it != last; ++it ) std::cout << *it << ' '; std::cout << std::endl; return 0; }输出是
1 4 25 73如果要替换声明
auto last = std::lower_bound( v.begin(), v.end(), 100 );对于
auto last = std::lower_bound( v.begin(), v.end(), 50 );然后输出将是
1 4 25等等。:)
The simplest way is to use standard algorithm std::lower_bound
For example
#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v = { 1, 4, 25, 73, 450 }; auto last = std::lower_bound( v.begin(), v.end(), 100 ); for ( auto it = v.begin(); it != last; ++it ) std::cout << *it << ' '; std::cout << std::endl; return 0; }The output is
1 4 25 73If to substitute statement
auto last = std::lower_bound( v.begin(), v.end(), 100 );for
auto last = std::lower_bound( v.begin(), v.end(), 50 );then the output will be
1 4 25And so on.:)
更多推荐
发布评论