I have a prime generator based on what I've seen in python by Sieve of Eratosthenes so this generator basically generate prime numbers with good performances.
What I would want is to use the range based loop on a range of prime number so here is what I did :
//Consider prime_generator a class with both operator*, operator!= and operator< overloaded
class primes_range {
private:
unsigned int max;
public:
primes_range(unsigned int max) : max(max) {}
prime_generator begin() const {
return prime_generator(); //so this begin from 2 to
//infinity and beyond but of course
//all primes
}
prime_generator end() const {
prime_generator result;
for (:*result < max; ++result) {} //so this thing actually create a
//generator and increment it until it
//gives the first prime number
//under max so it basically do
//all the work that I don't
//want it to do now
return rest;
}
};
So in my main, I would want to use the range-based loop, that's the point of the primes_range class.
int main() {
for (auto && i : primes_range(10)) { //So here, this is silly because
//the range-based loop will use end()
//wich will calculate all the prime
//numbers at the very beginning
//and i will increment apart from
//this starting process
cout << i << endl;
}
return 0;
}
Of course instead I could use a simple loop :
int main() {
for (prime_generator pg; *pg < 10; ++pg) {
cout << *pg << endl;
}
return 0;
}
But because the range-base loop is easier to read and prevent to use the operator*, I would want to use it instead, so my question is : Is there a way to make the range-base loop use another operator than != (in this case, I want it to stay inferior to max so it should use >=) ? Maybe overloard a particular function for primes_range or specialize a comparator ?
Aucun commentaire:
Enregistrer un commentaire