实现类似Python的Range
#define crange(fir, ...) std::views::iota(0 __VA_OPT__(+(fir)), __VA_OPT__(__VA_ARGS__ - (fir) +) (fir))
const auto j = 10;
for (auto i : crange(3, j))
{
// ok
}
Gosper's Hack
生成C_n^k个n元集合所有k元子集的算法.
void GospersHack(int k, int n)
{
int cur = (1 << k) - 1;
int limit = (1 << n);
while (cur < limit)
{
// do something
int lb = cur & -cur;
int r = cur + lb;
cur = ((r ^ cur) >> __builtin_ctz(lb) + 2) | r;
// 或:cur = (((r ^ cur) >> 2) / lb) | r;
}
}
// void GospersHack(3, 5)
// 00111
// 01011
// 01101
// 01110
// 10011
// 10101
// 10110
// 11001
// 11010
// 11100
Kahan Sum
用以低损失的求一列32位浮点数的和
float kahanSum(vector<float> nums) {
float sum = 0.0f;
float c = 0.0f;
for (auto num : nums) {
float y = num - c;
float t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
简单求某个值在结构体的偏移位
#define OFFSET(STRU, VAR) (unsigned)((void *)(&(((STRU*)(0x8))->VAR)) - 0x8)
#include <cstdio>
int main()
{
struct alignas(8) stu{
long a;
unsigned x;
char t[3];
};
printf("%d", OFFSET(stu, t[2]));
}