【CPP】随手记

目录

  • 1. 随机数
  • 2. 获取应用程序文件名
  • 3. 字符串分割
  • 4. 日志

1. 随机数

#include 
#include 

/// @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 

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 

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 
#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

你可能感兴趣的:(杂项,c++,算法,开发语言)