【CPP】随手记

1. 随机数

#include <chrono>
#include <random>

/// @brief 生成随机数
/// @details 生成的随机数范围[@param min, @param max]
/// @tparam[in] T 随机数的数据类型
/// @param[in] _max 随机数的最大值(闭区间)
/// @param[in] _min 随机数的最小值(闭区间)
/// @return 随机数
template <class T>
T GenRand(T _max, T _min = 0) {
  static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "T must be an integral or float type");
  std::default_random_engine       e(std::chrono::system_clock::now().time_since_epoch().count());
  std::uniform_int_distribution<T> u(_min, _max);
  return u(e);
}

2. 获取应用程序文件名

#include <string>

std::string GetAppName(int argc, char *argv[]) {
  std::string            fullName(argv[0]);
  std::string::size_type pos = fullName.find_last_of('/');
  if (pos == std::string::npos) {
    pos = fullName.find_last_of('\\');
    if (pos == std::string::npos) {
      return nullptr;
    }
  }

  return fullName.substr(pos + 1);
}

3. 字符串分割

#include <regex>

std::vector<std::string> stringSplit(const std::string &str, char delim) {
  std::string              s(1, delim);
  std::regex               reg(s);
  std::vector<std::string> elems(std::sregex_token_iterator(str.begin(), str.end(), reg, -1),
                                 std::sregex_token_iterator());
  return elems;
}

4. 日志

#ifndef LOG_HELPER_H_
#define LOG_HELPER_H_

#ifdef __cplusplus
extern "C" {
#endif

#ifndef NDEBUG
#include <stdio.h>
#define LOG_MSG(logType, fmt, ...)                                                                               \
  do {                                                                                                           \
    const char* format = "[%s] [%s] [%s] [%s] [%s] [%d] -> " fmt "\n";                                           \
    (void)fprintf(stderr, format, __DATE__, __TIME__, logType, __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  } while (0)

#define LOG_DEB(fmt, ...) LOG_MSG("DEB", fmt, ##__VA_ARGS__)
#define LOG_INF(fmt, ...) LOG_MSG("INF", fmt, ##__VA_ARGS__)
#define LOG_WAR(fmt, ...) LOG_MSG("WAR", fmt, ##__VA_ARGS__)
#define LOG_ERR(fmt, ...) LOG_MSG("ERR", fmt, ##__VA_ARGS__)
#define LOG_FAT(fmt, ...) LOG_MSG("FAT", fmt, ##__VA_ARGS__)
#else
#define LOG(logType, fmt, ...)
#define LOG_DEB(fmt, ...)
#define LOG_INF(fmt, ...)
#define LOG_WAR(fmt, ...)
#define LOG_ERR(fmt, ...)
#define LOG_FAT(fmt, ...)
#endif

#ifdef __cplusplus
}
#endif
#endif

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhy29563

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值