Random Iterator Mod 5
Description:
Example:
Note
Idea:
主要是注意一下取下一个数不能多次,所以next()和hasNext()要设计好。
Code:
只是个思想,这个程序跑不了,因为class Iterator没有implement。
#include <iostream>
#include <vector>
#include <climits>
#include <cassert>
using namespace std;
class Iterator {
public:
Iterator(const vector<int>& nums);
Iterator(const Iterator& iter);
virtual ~Iterator();
// Returns the next element in the iteration.
int next();
// Returns true if the iteration has more elements.
bool hasNext();
void remove();
};
class ModFiveIterator: public Iterator{
private:
bool flag_called;
bool flag_hasNext;
int next_random;
public:
ModFiveIterator(): flag_called(false), flag_hasNext(true) {}
bool hasNext(){
if(!flag_called){
next_random=Iterator::next();
while(Iterator::hasNext() && next_random%5!=0){
next_random=Iterator::next();
}
flag_called=true;
flag_hasNext = next_random%5==0 ? true: false;
}
return flag_hasNext;
}
int next(){
if(!hasNext()) {
throw runtime_error("no next.");
}
flag_called=false;
return next_random;
}
};