├── AutoObjectPool自动归还的对象池.cpp ├── CaseSwitch字符串大小写互换.cpp ├── CheckDuplicate判断数组重复元素.cpp ├── CheckTypeListUnique模板元编程TypeList判断重复元素.cpp ├── DoubleDispatch双分派.cpp ├── Fibonacci斐波那契数列.cpp ├── IntegerSort整数排序.cpp ├── IsPalindrome判断回文数.cpp ├── MetaQuickSort编译期快速排序(模板元编程).cpp ├── NoRepeatNum去重复数字.cpp ├── NumberOf1Bits二进制1的个数.cpp ├── PrintPrimeNumber打印质数.cpp ├── PrivateAccess访问私有成员变量.cpp ├── QuickIndex模板元编程Typelist快速下标访问.cpp ├── ReplaceType类型替换(模板元编程).cpp ├── ReverseBits32颠倒二进制位.cpp ├── TupleCartesian元祖的笛卡尔积.cpp └── TupleHash元组的哈希函数.cpp /AutoObjectPool自动归还的对象池.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | template class ObjectPool { 9 | private: 10 | using Storage = std::pair>; 11 | std::vector> v; 12 | std::mutex m; 13 | public: 14 | std::shared_ptr acquire() { 15 | std::lock_guard l(m); 16 | const std::shared_ptr> keeper = std::make_shared>(); 17 | auto iter = v.end(); 18 | while((iter = std::find_if(v.begin(), v.end(), [](const std::shared_ptr &s){ return s->second.lock() == nullptr; })) == v.end()) 19 | v.push_back(std::make_shared()); 20 | (*iter)->second = keeper; 21 | *keeper = *iter; 22 | return std::shared_ptr(keeper, &(*iter)->first); 23 | } 24 | }; 25 | 26 | int main() 27 | { 28 | std::shared_ptr> op = std::make_shared>(); 29 | auto a = op->acquire(); 30 | { 31 | auto b = op->acquire(), c = op->acquire(); 32 | std::cout << a.get() << std::endl; 33 | std::cout << b.get() << std::endl; 34 | std::cout << c.get() << std::endl; 35 | } 36 | auto e = op->acquire(); 37 | std::cout << e.get() << std::endl; 38 | *e = "still alive"; 39 | op = nullptr; 40 | std::cout << *e << std::endl; 41 | } 42 | -------------------------------------------------------------------------------- /CaseSwitch字符串大小写互换.cpp: -------------------------------------------------------------------------------- 1 | #include // cin cout 2 | #include // istreambuf_iterator ostreambuf_iterator 3 | #include // toupper tolower 4 | #include // transform 5 | 6 | using namespace std; 7 | int main() 8 | { 9 | // 1. 利用transform和流迭代器直接处理输入输出 10 | // 2. 利用按位异或的性质(源字符、大写、小写之中去掉两个重复的) 11 | // 3. 利用lambda表达式作为处理的函数对象 12 | transform(istreambuf_iterator(cin), istreambuf_iterator(), ostreambuf_iterator(cout), [](char c) { return c ^ toupper(c) ^ tolower(c); }); 13 | } -------------------------------------------------------------------------------- /CheckDuplicate判断数组重复元素.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MoeMod/MagicCpp/c741f6c2661a46f77b5687dacd900bb6cea3b3f6/CheckDuplicate判断数组重复元素.cpp -------------------------------------------------------------------------------- /CheckTypeListUnique模板元编程TypeList判断重复元素.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // C++17 std::conjunction does this... however I use just C++11 5 | template auto SfinaeConjunction(decltype(Args(), std::true_type())...) -> std::true_type; 6 | template auto SfinaeConjunction(...) -> std::false_type; 7 | template struct Conjunction : decltype(SfinaeConjunction(Args()...)) {}; 8 | 9 | // If all types are unique, Tag can be deduced. Sfinae based on that. 10 | template struct Tag {}; 11 | template static auto SfinaeHelper(const Tag &) -> std::true_type; 12 | template static auto SfinaeHelper(...) -> std::false_type; 13 | 14 | template struct CheckTypeListUniqueImpl; 15 | template class L, class...Args, std::size_t...I> struct CheckTypeListUniqueImpl, std::index_sequence> 16 | { 17 | struct Foo : Tag... {}; 18 | using type = Conjunction( Foo{} ))...>; 19 | }; 20 | 21 | // just make_index_sequence and forward 22 | template struct CheckTypeListUnique; 23 | template class L, class...Args> struct CheckTypeListUnique> 24 | : CheckTypeListUniqueImpl, std::index_sequence_for>::type {}; 25 | 26 | // simple test case 27 | template struct TypeList; 28 | int main() 29 | { 30 | using A = TypeList; 31 | using B = TypeList; 32 | std::cout << CheckTypeListUnique::value << CheckTypeListUnique::value << std::endl; 33 | } 34 | -------------------------------------------------------------------------------- /DoubleDispatch双分派.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MoeMod/MagicCpp/c741f6c2661a46f77b5687dacd900bb6cea3b3f6/DoubleDispatch双分派.cpp -------------------------------------------------------------------------------- /Fibonacci斐波那契数列.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // 使用模板计算0~92的斐波那契数 6 | template struct F : std::integral_constant::value + F::value> {}; 7 | template<> struct F<0> : std::integral_constant {}; 8 | template<> struct F<1> : std::integral_constant {}; 9 | 10 | // 将结果填充至数组 11 | template 12 | constexpr std::array buildArray(std::index_sequence) 13 | { 14 | return { F::value... }; 15 | } 16 | auto arr = buildArray(std::make_index_sequence<93>()); 17 | 18 | int main() 19 | { 20 | using namespace std; 21 | int i = 0; 22 | cin >> i; 23 | cout << arr[i] << endl; 24 | } -------------------------------------------------------------------------------- /IntegerSort整数排序.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() 8 | { 9 | /*std::vector v((std::istream_iterator(std::cin)), (std::istream_iterator())); // 输入数据到数组(按Ctrl+Z结束) 10 | std::sort(v.begin(), v.end()); // 对数组从小到大排序*/ 11 | 12 | std::multiset v((std::istream_iterator(std::cin)), (std::istream_iterator())); // 利用set自动排序 13 | std::copy(v.begin(), v.end(), std::ostream_iterator(std::cout, " ")); // 从数组输出数据 14 | } 15 | -------------------------------------------------------------------------------- /IsPalindrome判断回文数.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // https://leetcode-cn.com/problems/palindrome-number/ 8 | 9 | bool isPalindrome(int x) 10 | { 11 | auto str = std::to_string(x); 12 | return std::mismatch(str.cbegin(), str.cend(), str.crbegin()).first == str.cend(); 13 | } 14 | 15 | int main() 16 | { 17 | uint32_t n = *istream_iterator(cin); 18 | cout << isPalindrome(n) << endl; 19 | } -------------------------------------------------------------------------------- /MetaQuickSort编译期快速排序(模板元编程).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | templateclass F> struct NotFn1 6 | { 7 | template struct type 8 | { 9 | static constexpr bool value = !F::value; 10 | }; 11 | }; 12 | 13 | template class UnaryFunc> struct AppendIf; 14 | templateclass L, class...T, class Elem, template class UnaryFunc> struct AppendIf, Elem, UnaryFunc> 15 | { 16 | using type = typename std::conditional::value, L, L>::type; 17 | }; 18 | 19 | template class UnaryFunc> struct RemoveIf; 20 | templateclass L, class...AllElems, template class UnaryFunc> struct RemoveIf, UnaryFunc> 21 | { 22 | template struct filter; 23 | template struct filter> 24 | { 25 | using type = L; 26 | }; 27 | template struct filter, First, Rest...> 28 | { 29 | using type = typename filter, First, UnaryFunc>::type, Rest...>::type; 30 | }; 31 | using type = typename filter, AllElems...>::type; 32 | }; 33 | 34 | template class DivideFunc> struct Partition 35 | { 36 | using left = typename RemoveIf::type; 37 | using right = typename RemoveIf::template type>::type; 38 | using type = std::pair; 39 | }; 40 | 41 | template struct ListCat; 42 | template struct ListCat 43 | { 44 | using type = First; 45 | }; 46 | templateclass L, class...A, class...B, class...Rest> struct ListCat, L, Rest...> 47 | { 48 | using type = typename ListCat, Rest...>::type; 49 | }; 50 | 51 | template class CompareFunc> struct QSort; 52 | templateclass L, class First, class...Rest, template class CompareFunc> struct QSort, CompareFunc> 53 | { 54 | template 55 | struct BindDivided : CompareFunc {}; 56 | using divided = Partition, NotFn1::template type>; 57 | using type = typename ListCat< 58 | typename QSort::type, 59 | L, 60 | typename QSort::type 61 | >::type; 62 | }; 63 | templateclass L, template class CompareFunc> struct QSort, CompareFunc> 64 | { 65 | using type = L<>; 66 | }; 67 | 68 | template struct SizeofCompare : std::integral_constant {}; 69 | 70 | int main() 71 | { 72 | using A = std::tuple; 73 | using B = typename QSort::type; 74 | std::cout << typeid(B).name() << std::endl; 75 | } -------------------------------------------------------------------------------- /NoRepeatNum去重复数字.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MoeMod/MagicCpp/c741f6c2661a46f77b5687dacd900bb6cea3b3f6/NoRepeatNum去重复数字.cpp -------------------------------------------------------------------------------- /NumberOf1Bits二进制1的个数.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // https://leetcode-cn.com/problems/number-of-1-bits/ 6 | 7 | int hammingWeight(uint32_t n) 8 | { 9 | n = (n & 0x55555555) + ((n >> 1) & 0x55555555); 10 | n = (n & 0x33333333) + ((n >> 2) & 0x33333333); 11 | n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F); 12 | n = (n & 0x00FF00FF) + ((n >> 8) & 0x00FF00FF); 13 | n = (n & 0x0000FFFF) + ((n >> 16) & 0x0000FFFF); 14 | return n; 15 | } 16 | 17 | int main() 18 | { 19 | uint32_t n = *istream_iterator(cin); 20 | cout << hammingWeight(n) << endl; 21 | } -------------------------------------------------------------------------------- /PrintPrimeNumber打印质数.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | constexpr size_t log2(size_t N) 6 | { 7 | return N == 1 ? 0 : log2(N >> 1) + 1; 8 | } 9 | 10 | template struct SequenceCat; 11 | template struct SequenceCat { using type = A; }; 12 | template struct SequenceCat, std::index_sequence> 13 | { 14 | using type = std::index_sequence; 15 | }; 16 | template struct SequenceCat 17 | : SequenceCat< 18 | typename SequenceCat::type, 19 | typename SequenceCat::type 20 | >{}; 21 | 22 | template class F> struct SequenceRemoveIf; 23 | template class F> struct SequenceRemoveIf , F> 24 | : SequenceCat< 25 | typename std::conditional< 26 | F::value, 27 | std::index_sequence<>, 28 | std::index_sequence 29 | >::type... 30 | >{}; 31 | template class F> struct SequenceRemoveIf , F> 32 | { 33 | using type = std::index_sequence<>; 34 | }; 35 | 36 | template struct SequenceAdd; 37 | template struct SequenceAdd, N> 38 | { 39 | using type = std::index_sequence<(I + N)...>; 40 | }; 41 | 42 | template struct MakePrimeSequence 43 | { 44 | template struct Process; 45 | template struct Process> 46 | { 47 | template struct lambda : std::integral_constant First && X % First == 0)> {}; 48 | 49 | using type = typename Process< 50 | typename SequenceRemoveIf::type, 51 | typename SequenceRemoveIf, lambda>::type 52 | >::type; 53 | }; 54 | template struct Process> 55 | { 56 | using type = Seq; 57 | }; 58 | 59 | using type = typename Process< 60 | std::make_index_sequence, 61 | typename SequenceAdd, 2>::type 62 | >::type; 63 | }; 64 | 65 | template 66 | constexpr auto SequenceToArray(std::index_sequence) -> std::array 67 | { 68 | return {I...}; 69 | } 70 | 71 | constexpr size_t N = 2000; 72 | constexpr auto PrimeTable = SequenceToArray(typename MakePrimeSequence::type()); 73 | 74 | int main() 75 | { 76 | for(auto i : PrimeTable) 77 | std::cout << i << std::endl; 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /PrivateAccess访问私有成员变量.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class A { 4 | private: 5 | int val = 0; 6 | public: 7 | virtual int get() const { 8 | return val; 9 | } 10 | }; 11 | 12 | constexpr int A::* get_private(); 13 | template struct hack_a { 14 | friend constexpr int A::* get_private() { return Ptr; } 15 | }; 16 | template struct hack_a<&A::val>; 17 | 18 | int main() { 19 | A a; 20 | constexpr int A::* p = get_private(); 21 | std::cout << a.get() << std::endl; 22 | a.*p = 233; 23 | std::cout << a.get() << std::endl; 24 | } -------------------------------------------------------------------------------- /QuickIndex模板元编程Typelist快速下标访问.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | namespace Dalao { 5 | 6 | template struct type_identity { using type = T; }; 7 | template struct MakeIndexFinder; 8 | template struct MakeIndexFinder> 9 | { 10 | template type_identity operator()(decltype(I, void()) *..., T *, ...); 11 | }; 12 | template struct ListFind; 13 | templateclass L, class...Ts> struct ListFind> 14 | : decltype( MakeIndexFinder>()(typename type_identity::type()...) ) {}; 15 | 16 | } 17 | 18 | namespace Modern { 19 | 20 | template struct Indexed { using type = T; }; 21 | template struct MakeIndexFinder 22 | { 23 | template struct impl; 24 | template struct impl> : Indexed... {}; 25 | using type = impl>; 26 | }; 27 | template auto ListFindHelper(const Indexed &) -> Indexed; 28 | template struct ListFind; 29 | templateclass L, class...Ts> struct ListFind> 30 | : decltype(ListFindHelper(typename MakeIndexFinder::type())) {}; 31 | 32 | } 33 | 34 | namespace Naive { 35 | 36 | template struct ListFind; 37 | templateclass L, class First, class...Rest> struct ListFind> 38 | : ListFind> {}; 39 | templateclass L, class First, class...Rest> struct ListFind<0, L> 40 | { 41 | using type = First; 42 | }; 43 | 44 | } 45 | 46 | // Make some test case 47 | template struct MakeTypelist; 48 | template struct MakeTypelist> 49 | { 50 | using type = std::tuple...>; 51 | }; 52 | int main() 53 | { 54 | using A = MakeTypelist>::type; 55 | 56 | #define X 1 57 | 58 | #if X == 1 59 | using B = Dalao::ListFind<255, A>::type; 60 | #elif X == 2 61 | using B = Modern::ListFind<255, A>::type; 62 | #else 63 | using B = Naive::ListFind<255, A>::type; 64 | #endif 65 | std::cout << typeid(B).name() << std::endl; 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /ReplaceType类型替换(模板元编程).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | struct identity 5 | { 6 | using type = T; 7 | }; 8 | 9 | template 10 | struct replace_type : identity {}; 11 | 12 | template 13 | struct replace_type : identity {}; 14 | 15 | // functions with x 16 | template 17 | struct replace_type 18 | { 19 | using type = typename replace_type::type(typename replace_type::type...); 20 | }; 21 | 22 | // C++17 23 | #if __cplusplus >= 201703L 24 | template 25 | struct replace_type 26 | { 27 | using type = typename replace_type::type (*) (typename replace_type::type...) noexcept; 28 | }; 29 | #endif 30 | 31 | // template class with x 32 | template class obj, class...Args> 33 | struct replace_type, x, y> 34 | { 35 | using type = obj::type...>; 36 | }; 37 | 38 | template 39 | struct replace_type 40 | { 41 | using type = typename replace_type::type [i]; 42 | }; 43 | 44 | template 45 | struct replace_type : identity::type> {}; 46 | 47 | template 48 | struct replace_type : identity::type *> {}; 49 | 50 | template 51 | struct replace_type : identity::type &> {}; 52 | 53 | template 54 | struct replace_type : identity::type &&> {}; 55 | 56 | int main() 57 | { 58 | std::cout << typeid(replace_type ::type).name() << std::endl; 59 | } -------------------------------------------------------------------------------- /ReverseBits32颠倒二进制位.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | // https://leetcode-cn.com/problems/reverse-bits/ 6 | 7 | uint32_t reverseBits(uint32_t n) 8 | { 9 | n = ((n & 0x55555555) << 1) | ((n & 0xAAAAAAAA) >> 1); 10 | n = ((n & 0x33333333) << 2) | ((n & 0xCCCCCCCC) >> 2); 11 | n = ((n & 0x0F0F0F0F) << 4) | ((n & 0xF0F0F0F0) >> 4); 12 | n = ((n & 0x00FF00FF) << 8) | ((n & 0xFF00FF00) >> 8); 13 | n = ((n & 0x0000FFFF) << 16) | ((n & 0xFFFF0000) >> 16); 14 | return n; 15 | } 16 | 17 | int main() 18 | { 19 | uint32_t n = *istream_iterator(cin); 20 | cout << reverseBits(n) << endl; 21 | } -------------------------------------------------------------------------------- /TupleCartesian元祖的笛卡尔积.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | template 5 | constexpr auto cart_impl(Tuple1&& lhs, Tuple2&& rhs, std::index_sequence<0>, 6 | typename std::enable_if<(std::tuple_size::type>::value == std::tuple_size::type>::value == 1)>::type * = nullptr) 7 | { 8 | using T1 = typename std::tuple_element<0, typename std::decay::type >::type; 9 | using T2 = typename std::tuple_element<0, typename std::decay::type >::type; 10 | return std::tuple>(std::pair(std::get<0>(std::forward(lhs)), std::get<0>(std::forward(rhs)))); 11 | } 12 | 13 | template 14 | constexpr auto cart_impl(const std::tuple& lhs, Tuple2&& rhs, std::index_sequence, 15 | typename std::enable_if::type>::value != 1>::type * = nullptr) 16 | { 17 | return std::tuple_cat(cart_impl( 18 | lhs, 19 | std::tuple::type>::type>(std::get(std::forward(rhs))), 20 | std::index_sequence<0>() 21 | )...); 22 | } 23 | 24 | template 25 | constexpr auto cart_impl(Tuple1&& lhs, Tuple2&& rhs, std::index_sequence, 26 | typename std::enable_if::type>::value != 1>::type * = nullptr) 27 | { 28 | return std::tuple_cat(cart_impl( 29 | std::tuple::type>::type>(std::get(std::forward(lhs))), 30 | rhs, 31 | std::make_index_sequence::type >::value>() 32 | )...); 33 | } 34 | 35 | template 36 | constexpr auto cart(Tuple1&& lhs, Tuple2&& rhs) 37 | { 38 | return cart_impl(std::forward(lhs), std::forward(rhs), std::make_index_sequence::type >::value>()); 39 | } 40 | 41 | int main() 42 | { 43 | int x = 1, y = 2, z = 3; 44 | auto tuple1 = std::tie(x, y, z); 45 | auto tuple2 = std::make_tuple("a", "b"); 46 | auto tuple3 = cart(tuple2, tuple1); 47 | std::cout << typeid(tuple3).name() << std::endl; 48 | return 0; 49 | } -------------------------------------------------------------------------------- /TupleHash元组的哈希函数.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | template struct hash> 7 | { 8 | template 9 | std::size_t hash_impl(const tuple& t, std::index_sequence) const 10 | { 11 | return (hash()(std::get(t)) ^ ...); 12 | } 13 | std::size_t operator()(const tuple& t) const 14 | { 15 | return hash_impl(t, std::index_sequence_for()); 16 | } 17 | }; 18 | 19 | int main() 20 | { 21 | auto t = std::make_tuple(123, 456); 22 | auto t2 = std::make_tuple(123, 456); 23 | std::cout << hash()(t) << std::endl; 24 | std::cout << hash()(t2) << std::endl; 25 | } --------------------------------------------------------------------------------