Чтобы уменьшить дублирование кода, я создал макрос C и шаблон C++ для конструкции цикла, показанной ниже:
Код: Выделить всё
template
static inline void
for_loop_pairs(int at, int loops, const F fun) {
int right = MIN(loops, N - at - 1);
int left = loops - right;
while (right) {
int next = at + 1;
fun(at, next);
at = next;
next++;
right--;
}
if (left) {
fun(N - 1, 0);
left--;
at = 0;
while (left) {
int next = at + 1;
fun(at, next);
at = next;
next++;
left--;
}
}
}
#define FOR_LOOP_PAIRS(at, loops, fun) \
int right = MIN(loops, N - at - 1); \
int left = loops - right; \
int k0 = at; \
while (right) { \
int k1 = k0 + 1; \
fun; \
k0 = k1; \
k1++; \
right--; \
} \
if (left) { \
k0 = N - 1; \
int k1 = 0; \
fun; \
left--; \
k0 = 0; \
while (left) { \
k1 = k0 + 1; \
fun; \
k0 = k1; \
k1++; \
left--; \
} \
}
Код: Выделить всё
NКод: Выделить всё
FOR_LOOP_PAIRS(start, loops, {
// Do stuff with k0 and k1, which are the indices.
});
for_loop_pairs(start, loops, [&](int k0, int k1) {
// Do stuff with k0 and k1 which are the indices.
});
Команда компиляции: g++ -Wall -Werror -fPIC -march=native -mtune=native - O3 -fomit-frame-pointer fname.cpp gcc версии 7.4.0.
Подробнее здесь: https://stackoverflow.com/questions/586 ... -macro-why
Мобильная версия