分享

c++奇技淫巧

 C语言与CPP编程 2022-03-31

2022 精心整理的 C语言/C++ 语言学习宝藏,值得收藏~_程序员编程指南的博客-CSDN博客知名大学计算机系开源课程收录:浙江大学课程攻略共享计划清华大学计算机系课程攻略上海交通大学课程资料分享北京航空航天大学(北航)课程作业资料共享计划华北电力大学计算机系课程攻略北京邮电大学计算机考研信息汇总C++从入门到“精通“,我踩过的坑希望你可以绕着走_程序员编程指南的博客-CSDN博客1 c++ 发展方向实验室开发C++绝对是工科生中的第一大语言,C++兼具面向过程以及面向对象的特性,既拥有比较优秀的运行速度,又有良好的大型项目开发能力,那简直可以制霸高校实验室了。后端开发学了https://blog.csdn.net/weixin_41055260/article/details/123793376

1 C++ 写一个函数,用模板函数的特例化这个属性得到一个数组的长度。

#include <iostream>
using namespace std;
 
template <typename Type, size_t N>
inline size_t GetArrayLength(const Type(&)[N])
{
    return N;
}
 
void main()
{
    int a []= {,,};
    cout << GetArrayLength(a) << endl;
    system("pause");
}

2 get/set自动生成

通过宏定义来实现

#define ClassVar(permission, type, name, value, funcname)           public:                                                             void Set##funcname(type v_val) { name = v_val; }                type Get##funcname() const { return name; }                 permission:                                                         type name = value;

使用例子:

ClassVar(private, int, cnt_, 0, Count)

生成

public:
    void SetCount(int v_val) { cnt_ = v_val; }
    int GetCount() const { return cnt_; }
private:
    int cnt_ = 0;

3 inline(内联)关键字

inline int max(int a, int b)     
    return a > b ? a : b                         
}                                
                                           
int main()                                  
{                                         
    int a, b, c;                           
    cin >> a >> b >> c;                   
                                           
    cout << max(a, b) << endl;  
    return 0;                            
}  

4 释放vector的存储空间

reverse的源代码,可以看到当reserve(0)时,并没有释放多余空间的逻辑

template 
void
vector<_Tp, _Allocator>::reserve(size_type __n)
{
 if (__n > capacity())
 {
 allocator_type& __a = this->__alloc();
 __split_buffer __v(__n, size(), __a);
 __swap_out_circular_buffer(__v);
 }
}

5 宏自身迭代

#define BOOST_PP_COMMA_IF(cond) BOOST_PP_IF(cond, BOOST_PP_COMMA, BOOST_PP_EMPTY)()
#define BOOST_PP_IF(cond, t, f) BOOST_PP_IIF(BOOST_PP_BOOL(cond), t, f)
#define BOOST_PP_IIF(bit, t, f) BOOST_PP_IIF_I(bit, t, f)
#define BOOST_PP_IIF_I(bit, t, f) BOOST_PP_IIF_ ## bit(t, f)
# define BOOST_PP_IIF_0(t, f) f
# define BOOST_PP_IIF_1(t, f) t
#define BOOST_PP_BOOL(x) BOOST_PP_BOOL_I(x)
# define BOOST_PP_BOOL_I(x) BOOST_PP_BOOL_ ## x
# define BOOST_PP_BOOL_0 0
# define BOOST_PP_BOOL_1 1
# define BOOST_PP_BOOL_2 1
... ...
# define BOOST_PP_BOOL_256 1

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多