c++ - Shortest way to obtain a sublist of a sorted list of values lying in a certain interval -
today asking myself might shortest possible code obtain values in sorted vector std::vector<double>
, greater or equal a
, smaller or equal b
.
my first approach following:
#include <vector> #include <algorithm> #include <iterator> #include <iostream> // returns values in sortedvalues being greater equal start , smaller equal end; std::vector<double> cutvalues(const std::vector<double>& sortedvalues, double start, double end) { std::vector<double> ret; auto startiter=std::lower_bound(sortedvalues.begin(), sortedvalues.end(), start); auto stopiter = std::upper_bound(sortedvalues.begin(), sortedvalues.end(), end); std::copy(startiter, stopiter, std::back_inserter(ret)); return ret; } int main(int argc, char **args) { { auto ret = cutvalues({ 0.1,0.2,0.3 }, 0.1, 0.3); std::copy(ret.begin(), ret.end(), std::ostream_iterator<double>(std::cout, ",")); std::cout << std::endl; } { auto ret = cutvalues({ 0.12,0.2,0.31 }, 0.1, 0.3); std::copy(ret.begin(), ret.end(), std::ostream_iterator<double>(std::cout, ",")); std::cout << std::endl; } { auto ret = cutvalues({ 0.1,0.2,0.3 }, 0.2, 0.2); std::copy(ret.begin(), ret.end(), std::ostream_iterator<double>(std::cout, ",")); std::cout << std::endl; } }
my second thought simple following:
std::vector<double> cutvalues2(const std::vector<double>& sortedvalues, double start, double end) { std::vector<double> ret; std::copy_if(sortedvalues.begin(), sortedvalues.end(), std::back_inserter(ret), [&start, &end](auto v) { return v >= start && v <= end; }); return ret; }
but considering case of removing small portions large vector might have efficiency issues.
now i'm asking myself, if there there better ways it?
a bit changed first version:
std::vector<double> cutvalues(const std::vector<double>& sortedvalues, double start, double end) { auto startiter = std::lower_bound(sortedvalues.begin(), sortedvalues.end(), start); auto stopiter = std::upper_bound(startiter, sortedvalues.end(), end); return std::vector<double>(startiter, stopiter); }
Comments
Post a Comment