因此,假设我们要对小于或等于 100 的所有偶数正数迭代某个函数。我们可以这样做:
vector<int> v;
for (int i=0; i<=100; i+=2) v.push_back(i);
for_each(v.begin(), v.end(), ourFunction);
其他更简单的方法是:
for (int i=0; i<=100; i+=2) ourFunction(i);
现在,假设我们要迭代一个更复杂的集合。例如回文数(以 10 为底)小于 1000000。我们可以这样做:
inline int tenTo(int power) { int n= 1; for(int i=0; i<power; i++) n*=10; return n; }
vector<int> getPalindromial(int digits, bool firstCall = true,vector<int> &fakePalindromial = vector<int>()) {
if (digits == 1) {
// Base Case 1
vector<int> v;
fakePalindromial.push_back(0);
for (int i=1; i<=9; i++) {
v.push_back(i);
fakePalindromial.push_back(i);
}
return v;
} else if (digits == 2) {
// Base Case 2
vector<int> v;
fakePalindromial.push_back(0);
for (int i=11; i<=99; i += 11) {
v.push_back(i);
fakePalindromial.push_back(i);
}
return v;
} else {
if (firstCall) {
// If this is the first call, we built all the odd lenght numbers and the even length numbers and then we join them and return.
vector<int> v1 = getPalindromial(digits,false);
vector<int> v2 = getPalindromial(digits-1,false);
v1.insert(v1.end(), v2.begin(), v2.end());
return v1;
}
/* Recursive case:
* For each palindromical number with 2 less digits, we add each digit at start and at the end
*/
vector<int> v = getPalindromial(digits-2,false,fakePalindromial);
const int size = fakePalindromial.size();
for (int i=0; i<size; i++) {
const int n = fakePalindromial[i];
int nDigits = 1;
for (int i=0; i< digits-2; i++) {
nDigits *= 10;
}
/* Numbers with leading 0 are not really palindromical, but will be usefull to the functions building higher
* numbers ( 010 is not palindromical, but it is usefull for building 50105)
*/
int digit = 0;
fakePalindromial.push_back(10*(nDigits*digit + n) + digit);
for (int digit=1; digit<=9; digit++) {
v.push_back(10*(nDigits*digit + n) + digit);
fakePalindromial.push_back(10*(nDigits*digit + n) + digit);
}
}
// Clean the palindromical numbers that we have used
for (int i=0; i<size; i++) {
fakePalindromial.erase(fakePalindromial.begin());
}
return v;
}
}
进而:
vector<int> v = getPalindromial(6);
for_each(v.begin(), v.end(), ourFunction);
我们如何在不生成空洞集合然后对其进行迭代的情况下实现相同的目标?
(注意:getPalindromial 函数可能更简单,它是这样制作的,所以它更复杂)