ProgramAlgTrain/20240906/bitset.cpp
2024-09-07 13:51:17 +08:00

97 lines
2.2 KiB
C++

#include <any>
#include <array>
#include <climits>
#include <cstddef>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
using namespace std;
typedef unsigned int u8;
typedef int i8;
const u8 MAX = 1e5+1;
template<typename T>
struct std::formatter<std::vector<T>> {
constexpr auto parse(format_parse_context& ctx)const {
return ctx.begin();
}
constexpr auto format(const std::vector<T>& v, auto& ctx)const {
auto out = ctx.out();
std::format_to(out, "[");
for (size_t i = 0; i < v.size(); ++i) {
if (i > 0) {
std::format_to(out, ", ");
}
std::format_to(out, "{}", v[i]);
}
return std::format_to(out, "]");
}
};
constexpr std::array<u8, (size_t)MAX> initLog2() {
std::array<u8, (size_t)MAX> log2{};
log2[1] = 0;
for (int i = 2; i <= (int)MAX - 1; i++) {
log2[i] = log2[i / 2] + 1;
}
return log2;
}
class BitIntSet {
private:
constexpr static const std::array<u8, (size_t)MAX> log2 = initLog2();
public:
i8 data;
constexpr explicit BitIntSet(i8 n) : data{n} {}
constexpr int getLowbit() const {
return this->data & ((~this->data) + 1);
}
constexpr int getLowbit(u8 n) const {
return n & ((~n) + 1);
}
constexpr std::vector<u8> get1Dir() const {
std::vector<u8> ret;
int temp = this->data;
while (temp != 0) {
// #ifndef NDEBUG
// std::cout<<std::format("[Debug]the lowbit of {} is {}\n",temp,getLowbit(temp));
// #endif
ret.push_back(log2[getLowbit(temp)]);
temp -= getLowbit(temp);
}
return ret;
}
};
auto getTypeName(std::any &a){
return a.type().name();
}
template<class ...Args>
void print(const Args&...args){
((std::cout<<args),...);
}
template<typename... Args>
void println(const Args&...args){
((std::cout<<args<<" "),...);
endl(std::cout);
}
int main() {
int at =1;
println(at,"b",123,"c");
constexpr BitIntSet bit(257);
constexpr auto a = bit.data,b=bit.getLowbit();
auto c = bit.get1Dir();
std::cout<<a<<" "<<b<<" "<<c[0]<<" "<<c[1]<<std::endl;
}