本人很闲,这个想法是我自己想出的,如有雷同,那我就很唐。
使用方法:
for (<type> <name> : <begin> to <end>),定义一个 <type> <name> 变量并遍历 [<begin>, <end>]。
for (<type> <name> : <begin> until <end>),定义一个 <type> <name> 变量并遍历 [<begin>, <end>)。
需要注意,如果 <end> 是一个带 operator, 的表达式,需要用小括号括一下 <end>。
实现方法:将 to 和 until 替换为 ,标识符,,标识符和左参先结合然后和右参结合,生成一个可遍历的 range,使用 c++14 的 for: 对其遍历。
#include <type_traits>
#define to , fft_translator() ,
#define until , fft_translator_until() ,
struct fft_translator {};
struct fft_translator_until {};
template<typename T>
struct fft_range {
struct iterator {
T x;
const T &operator*() const { return x; }
bool operator!=(const iterator &b) const { return x != b.x; }
iterator &operator++() { ++x; return *this; }
};
T b, e;
iterator begin() const { return {b}; }
iterator end() const { return {e}; }
};
template<typename T>
struct fft_range_until_b { T b; };
template<typename T2, typename T>
fft_range<std::decay_t<T2> > operator,(fft_range<T2> ans, T e) {
ans.e = ++e;
return ans;
}
template<typename T>
fft_range<std::decay_t<T> > operator,(T &&b, fft_translator) {
fft_range<std::decay_t<T> > ans;
ans.b = b;
return ans;
}
template<typename T2, typename T>
fft_range<T2> operator,(fft_range_until_b<T2> ans_u, T e) {
fft_range<T2> ans;
ans.b = ans_u.b;
ans.e = e;
return ans;
}
template<typename T>
fft_range_until_b<std::decay_t<T> > operator,(T &&b, fft_translator_until) {
fft_range_until_b<std::decay_t<T> > ans;
ans.b = b;
return ans;
}使用示例:
#include <bits/stdc++.h>
using namespace std;
int main() {
for (int i : -10 to 10) {
cout << i << " ";
}
cout << endl;
vector<int> x{1, 10, -10, 999};
for (vector<int>::iterator i : x.begin() to x.end() - 1) {
cout << *i << " ";
}
cout << endl;
for (vector<int>::iterator i : x.begin() until x.end()) {
cout << *i << " ";
}
cout << endl;
for (vector<int>::reverse_iterator i : x.rbegin() until x.rend()) {
cout << *i << " ";
}
cout << endl;
return 0;
}期望输出:
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10
1 10 -10 999
1 10 -10 999
999 -10 10 1
补充:如果 #define from : 可能更优雅。
补充:fft 为 For-From-To 的缩写。