100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > C++日常用的函数总结

C++日常用的函数总结

时间:2023-05-06 09:36:23

相关推荐

C++日常用的函数总结

文章目录

windows&linux1. 检查路径是否存在2. 检查文件是否存在 windows API 部分1. 程序提权(提示申请使用管理员权限)2. 获得windows下的临时文件夹(C:\Users\_your_name_\AppData\Local\Temp) Linux 部分1. 使用popen检查命令输出中是否包含特定字段2. 使用bash中模糊的匹配方式(hell*world.cpp)匹配文件路径,并返回。使用linux中的glob函数3. 获取linux中可用的内存 字符串部分1. 窄字符串转宽字符串2. TCHAR* 转string3. QString去掉所有空格和回车4. 给定一个路径,返回上一层的路径5. 解析格式化字符串 文件操作1. 得到一个路径下所有文件列表2. 得到一个路径下所有文件列表23. 遍历目录下的所有文件,包括文件夹中的4. 获取硬盘大小(linux)5. 硬盘挂载检测,实现自动重新挂载6. 判断路径是否正确7. 将文件中的内容读取到string中 时间相关1. 将时间戳转成其他时间格式2. 计算程序耗时 STL&Boost1. Boost - HttpServer2. 删除容器中的满足特定条件的元素3. std::sort 排序4. 快速找到vector的一个元素,并定位到他的下标。 数学相关1. 求两点的直线距离2. 归一化系列函数3. 求两直线交点或两线段交点4. 按轮廓找01矩阵连通域5. 将多边形顶点按逆时针排序

windows&linux

1. 检查路径是否存在

bool directory_exists(const std::string &directory){struct stat buffer;// if any condition failsreturn (stat(directory.c_str(), &buffer) == 0) && (buffer.st_mode & S_IFDIR);;}

2. 检查文件是否存在

bool file_exists(const std::string &filename){struct stat buffer;return (stat(filename.c_str(), &buffer) == 0) && (buffer.st_mode & S_IFREG);}

windows API 部分

1. 程序提权(提示申请使用管理员权限)

/*** Creates elevated worker process.** \param[in] appPath path to elevated worker module* \param[in] cmdLine commandline to start elevated worker with** \return Handle to created process.*/static HANDLE create_elevated_worker(PWSTR appPath, PWSTR cmdLine){BOOL bSuccess = FALSE;SHELLEXECUTEINFOW exInfo = {0 };exInfo.cbSize = sizeof(exInfo);exInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE;exInfo.hwnd = NULL;exInfo.lpVerb = L"runas";exInfo.lpFile = appPath;exInfo.lpParameters = cmdLine;exInfo.lpDirectory = NULL;exInfo.nShow = SW_HIDE;/* exInfo.hInstApp is output parameter *//* exInfo.lpIDList, exInfo.lpClass, exInfo.hkeyClass, exInfo.dwHotKey, exInfo.DUMMYUNIONNAME* are ignored for our fMask value.*//* exInfo.hProcess is output parameter */bSuccess = ShellExecuteExW(&exInfo);if (FALSE == bSuccess){fprintf(stderr, "Failed to create worker process!\n");return INVALID_HANDLE_VALUE;}return exInfo.hProcess;}

2. 获得windows下的临时文件夹(C:\Users_your_name_\AppData\Local\Temp)

static const char* get_tmp_dir(){static char tmpdir[200] = {'\0' };if (tmpdir[0] == '\0'){#ifndef _MSC_VERstrcpy(tmpdir, "/tmp");#else// C:\Users\houxiao1\AppData\Local\TempGetTempPathA(sizeof(tmpdir) / 2, (LPSTR)tmpdir);#endif}return tmpdir;}

Linux 部分

1. 使用popen检查命令输出中是否包含特定字段

bool isExistInCmd(char* cmd, const char* key){FILE* fp = popen(cmd, "r");char buf[1024];if ((fp = popen(cmd, "r")) == NULL)perror("popen");while (fgets(buf, 1024, fp)){if (strstr(buf, key))return true;}return false;}

2. 使用bash中模糊的匹配方式(hell*world.cpp)匹配文件路径,并返回。使用linux中的glob函数

// 返回所有满足条件的文件路径#include <glob.h>static bool glob_files(const std::string& pattern, std::vector<std::string>& files){glob_t glob_result;memset(&glob_result, 0, sizeof(glob_result));int res = glob(pattern.c_str(), GLOB_TILDE, nullptr, &glob_result);if (res != 0){globfree(&glob_result);return false;}for (size_t i = 0; i < glob_result.gl_pathc; ++i) {files.emplace_back(std::string(glob_result.gl_pathv[i]));}globfree(&glob_result);return true;}

3. 获取linux中可用的内存

#include <fstream>#include <sstream>#include <string>// 获取linux系统可用内存void memory_utilization(float& fmemtotal, float& fmemfree, float& fmemvalid){std::string memtotal;std::string memfree;std::string memavail;std::string membufs;std::string key, value;std::string line;std::ifstream stream("/proc/meminfo");if(stream.is_open()){while (std::getline(stream, line)) {std::istringstream linestream(line);while(linestream >> key >> value) {if (key == "Memtotal:") {fmemtotal = std::stof(value);} else if(key == "MemFree:") {fmemfree = std::stof(value);} else if (key == "MemAvailable:") {fmemvalid = std::stof(value);}}}}stream.close();}

字符串部分

1. 窄字符串转宽字符串

static std::wstring s2ws(const std::string& s){std::string curlLocale = setlocale(LC_ALL, NULL);setlocale(LC_ALL, "chs");const char* _Source = s.c_str();size_t _Dsize = s.size() + 1;wchar_t* _Dest = new wchar_t[_Dsize];size_t i;mbstowcs_s(&i, _Dest, _Dsize, _Source, s.size());std::wstring result = _Dest;delete[] _Dest;setlocale(LC_ALL, curlLocale.c_str());return result;}

2. TCHAR* 转string

std::string convert2string(TCHAR * STR){int iLen = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, NULL);char* chRtn = new char[iLen * sizeof(char)];WideCharToMultiByte(CP_ACP, 0, STR, -1, chRtn, iLen, NULL, NULL);std::string str(chRtn);delete[] chRtn;return str;}

3. QString去掉所有空格和回车

copytxt = copytxt.simplified();// 简化,删除回车和多余的空格copytxt.replace(" ", "");

4. 给定一个路径,返回上一层的路径

// 返回上一层路径static std::string path_to_back(const std::string& path, int times = 1, char split = '/'){std::string path_res = path;for (int i= 0; i<times; i++) {path_res = path_res.substr(0, path_res.find_last_of(split));}return path_res;}

5. 解析格式化字符串

std::string string_vsnprintf(const std::string& format, va_list args) {// try firstint32_t try_size = 512;char try_buff[try_size];memset(try_buff, 0, try_size);std::string res;int32_t size_needed = std::vsnprintf(try_buff, try_size, format.c_str(), args);if (size_needed < try_size) {res.assign(try_buff, size_needed);} else {// try againchar buff_needed[size_needed+1];memset(buff_needed, 0, size_needed+1);int32_t size = std::vsnprintf(buff_needed, size_needed+1, format.c_str(), args);if (size >= 0) {res.assign(buff_needed, size_needed);} else {res.assign("", 0);}}// MISRA C++ : 6-6-5return res;}

std::string string_sprintf(const char* format, ...) {va_list args;va_start(args, format);std::string buff = string_vsnprintf(format, args);va_end(args);return buff;}

文件操作

1. 得到一个路径下所有文件列表

#include <vector>#include <string.h>#ifdef linux#include <unistd.h>#include <dirent.h>#endif#ifdef WIN32#include <direct.h>#include <io.h>#endifstd::vector<std::string> getFiles(const std::string& cate_dir){std::vector<std::string> files;//存放文件名#ifdef WIN32_finddata_t file;long lf;//输入文件夹路径if ((lf = _findfirst(cate_dir.c_str(), &file)) == -1) {cout << cate_dir << " not found!!!" << endl;}else {while (_findnext(lf, &file) == 0) {//输出文件名//cout<<file.name<<endl;if (strcmp(file.name, ".") == 0 || strcmp(file.name, "..") == 0)continue;files.push_back(file.name);}}_findclose(lf);#endif#ifdef linuxDIR *dir;struct dirent *ptr;char base[1000];if ((dir = opendir(cate_dir.c_str())) == NULL){perror("Open dir error...");exit(1);}while ((ptr = readdir(dir)) != NULL){if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) ///current dir OR parrent dircontinue;else if (ptr->d_type == 8) ///file//printf("d_name:%s/%s\n",basePath,ptr->d_name);files.push_back(ptr->d_name);else if (ptr->d_type == 10) ///link file//printf("d_name:%s/%s\n",basePath,ptr->d_name);continue;else if (ptr->d_type == 4) ///dir{continue;//files.push_back(ptr->d_name);/*memset(base,'\0',sizeof(base));strcpy(base,basePath);strcat(base,"/");strcat(base,ptr->d_nSame);readFileList(base);*/}}closedir(dir);#endif//排序,按从小到大排序sort(files.begin(), files.end());return files;}

2. 得到一个路径下所有文件列表2

static std::vector<std::string> get_file_list(const std::string& path, const std::string& filter = ".*"){std::vector<std::string> file_list;DIR *dirp;struct dirent *dp;dirp = opendir(path.c_str());while ((dp = readdir(dirp)) != NULL) {if(std::regex_match(dp->d_name, std::regex(filter))){file_list.push_back(std::string(dp->d_name ));}}(void) closedir(dirp);std::sort(file_list.begin(), file_list.end(), [](const std::string& s1, const std::string& s2){return pare(s2) < 0;});return file_list;}static int64_t get_file_size(const std::string& path){std::ifstream in(path);in.seekg(0, std::ios::end);return in.tellg();}

3. 遍历目录下的所有文件,包括文件夹中的

windows&linux

#include <dirent.h>#include <vector>#include <string>void load_files(const std::string& dirname, std::vector<std::string>& files){struct dirent * ptr;DIR* dir = opendir(dirname.c_str());while ((ptr = readdir(dir)) != NULL){files.push_back(ptr->d_name);}closedir(dir);}

4. 获取硬盘大小(linux)

struct statfs diskInfo;statfs("/mnt/mmcblk0p15/", &diskInfo);unsigned long long blocksize = diskInfo.f_bsize;//每个block里包含的字节数unsigned long long totalsize = blocksize * diskInfo.f_blocks; //总的字节数,f_blocks为block的数目printf("Total_size = %llu B = %llu KB = %llu MB = %llu GB\n",totalsize, totalsize >> 10, totalsize >> 20, totalsize >> 30);unsigned long long freeDisk = diskInfo.f_bfree * blocksize;//剩余空间的大小unsigned long long availableDisk = diskInfo.f_bavail * blocksize; //可用空间大小printf("Disk_free = %llu MB = %llu GB\nDisk_available = %llu MB = %llu GB\n",freeDisk >> 20, freeDisk >> 30, availableDisk >> 20, availableDisk >> 30);

5. 硬盘挂载检测,实现自动重新挂载

void check_availableDisk(){gCheckAvailableDiskThd = std::thread([]() {while (gRunning){if (!isExistInCmd("df -h", gServerConfig.diskMountOn.substr(0, gServerConfig.diskMountOn.size() - 1).c_str())){if (isExistInCmd("lsblk", "sda1")){// run mount.shsystem(("./mount.sh /dev/sda1 " + gServerConfig.diskMountOn).c_str());if (isExistInCmd("df -h", gServerConfig.diskMountOn.substr(0, gServerConfig.diskMountOn.size() - 1).c_str())){// success// g_mediaManager.restartVideoStorage();}else{// failed// send_error_message("mount error!", "The hard disk is disconnected and cannot be reconnected.");}}else{send_error_message("no disk error.", "Hard drive not found.");}}});}

#!/bin/bash# mount.sh $1 $2sudo umount $1sudo mkdir -p $2sudo rm -rf $2/*sudo mount $1 $2

6. 判断路径是否正确

access(gServerConfig.diskMountOn.c_str(), F_OK) == 0 // is true

7. 将文件中的内容读取到string中

static bool string_load(const std::string& file, std::string& content) {assert(!file.empty());FILE* fp = fopen(file.c_str(), "rb");if (fp == nullptr) {return false;}// check sizefseek(fp, 0, SEEK_END);size_t bufsize = ftell(fp);rewind(fp);// malloc bufferchar buf[bufsize + 1];memset(buf, 0, bufsize + 1);size_t res = fread(buf, 1, bufsize, fp);fclose(fp);if (res <= 0) {return false;}// to stringcontent = char_to_string(buf, bufsize);return true;}

时间相关

1. 将时间戳转成其他时间格式

// -8-17T9:53:54.000Zstd::string conv_timeType(const std::string & time){static char deli[7] = {'-', '-', 'T', ':', ':', '.', 'Z' };time_t rawtime(std::atoll(time.c_str()));struct tm * timeinfo;timeinfo = localtime(&rawtime);std::string ss = std::to_string(timeinfo->tm_year + 1900) + deli[0]+ std::to_string(timeinfo->tm_mon + 1) + deli[1]+ std::to_string(timeinfo->tm_mday) + deli[2]+ std::to_string(timeinfo->tm_hour) + deli[3]+ std::to_string(timeinfo->tm_min) + deli[4]+ std::to_string(timeinfo->tm_sec) + deli[5]+ "000" + deli[6];return ss;}

2. 计算程序耗时

gettimeofday可以精确到微秒。

struct timeval start;struct timeval end;unsigned long timer;gettimeofday(&start,NULL);printf("hello world!\n");gettimeofday(&end,NULL);timer = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec;printf("timer = %ld us\n",timer);

bash方法

#!/bin/bashfunction handle(){start=$(date +%s%N)start_ms=${start:0:16}$1end=$(date +%s%N)end_ms=${end:0:16}echo "cost time is:"echo "scale=6;($end_ms - $start_ms)/1000000" | bc}handle

STL&Boost

1. Boost - HttpServer

#include "server_http.hpp"using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;using boost::asio::ip::tcp;HttpServer gServer;int main(){// ...gServer.config.port = std::atoi(gServerConfig.inputServerIPPort.c_str()); // 8079gServer.resource["^/online/live/start$"]["POST"] = [](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) {// Retrieve string://auto content = request->content.string();// request->content.string() is a convenience function for:// stringstream ss;// ss << request->content.rdbuf();// auto content=ss.str();//#test//{//std::ofstream fs("../req.json");//fs << request->content.rdbuf();//fs.close();//}proc_get_live_url(response, request);/*{const std::string content(jsonRoot.ToString());*response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n"<< content;}*///response->write(request->path_match[0].str());// Alternatively, use one of the convenience functions, for instance:// response->write(content);};// ...}

2. 删除容器中的满足特定条件的元素

使用stl,神奇的完成这个任务。不过此函数并不保证稳定性,如有需要,应该进行重新排序。

// 下面的代码中,会删除满足Condition()的所有元素。Execution()释放Deferred资源。const auto pred = [](Deferred& d){return !d.Condition(); };auto itMatch = std::partition( defs.begin(), defs.end(), pred);const auto action = [](Deferred& d){d.Execution(); };std::for_each(itMatch, defs.end(), action);defs.erase(itMatch, defs.end());

3. std::sort 排序

auto comp = [](Deferred& d_1, Deferred& d_2) {return d_1 < d_2; };std::sort(defs.begin(), defs.end(), comp);

4. 快速找到vector的一个元素,并定位到他的下标。

常用于output并不是简单结构的时候,避免发生拷贝,又能方便使用。

size_t labelInd = std::distance(output.begin(), std::max_element(output.begin(), output.end()));

数学相关

1. 求两点的直线距离

很简单的三角定理,但是下面其他函数都用的到,所以就一并写在这里了。

double getP2PLength(const cv::Point2f & point1, const cv::Point2f & point2){return std::sqrt(std::pow(point1.x - point2.x, 2) + std::pow(point1.y - point2.y, 2));}

2. 归一化系列函数

第一种,最简单是就是限定最大值最小值,放缩到(0, 1)区间了。前提是,最大值和最小值都要是有限值。

x’ = (x-x_min) / (x_max - x_min);

第二种,平均归一化

第三种,非线性归一化。包括对数转换,反余切函数转换,或者其他特异函数。

3. 求两直线交点或两线段交点

已知直线1上两点line1_a, line1_b, 直线2上两点line2_a, line2_b。求交点cross_p, 若无交点返回(0,0)。函数返回false。

// It is known that there are two points on line 1(line1_a, line1_b),// and there are two points on line 2(line2_a, line2_b).// The intersection of the two lines is pont.// return false, if two straight lines have no intersection.bool getCrossPoint(const cv::Point2f & line1_a, const cv::Point2f & line1_b, const cv::Point2f & line2_a, const cv::Point2f & line2_b, cv::Point2f & cross_p){float a1 = line1_a.y - line1_b.y;float b1 = line1_b.x - line1_a.x;float c1 = line1_a.x * line1_b.y - line1_b.x * line1_a.y;float a3 = line2_a.y - line2_b.y;float b3 = line2_b.x - line2_a.x;float c3 = line2_a.x * line2_b.y - line2_b.x * line2_a.y;float D = a1 * b3 - a3 * b1;cross_p = cv::Point2f(0, 0);if (D == 0)return false;cross_p.x = (b1*c3 - b3 * c1) / D;cross_p.y = (a3*c1 - a1 * c3) / D;return true;}

如果要求两个线段的交点,可以再通过求交点和两个端点的距离,如果都小于线段的长度,则可判定两线段有交点。

// return true, If two line segments have intersection. otherwise return false.bool isHaveIntersectionAtLinesegment(const cv::Point2f & line1_a, const cv::Point2f & line1_b, const cv::Point2f & line2_a, const cv::Point2f & line2_b)cv::Point2f cross;float dis1 = CameraCalculate::getP2PLength(line1_a, line1_b);float dis2 = CameraCalculate::getP2PLength(line2_a, line2_b);if (TRACKERALGORITHM::getCrossPoint(line2_a, line2_b, line1_a, line1_b, cross) && CameraCalculate::getP2PLength(line1_a, cross) < dis1&& CameraCalculate::getP2PLength(cross, line1_b) < dis1&& CameraCalculate::getP2PLength(line2_a, cross) < dis2&& CameraCalculate::getP2PLength(line2_b, cross) < dis2)return true;elsereturn false;}

4. 按轮廓找01矩阵连通域

void bwLabel(const Mat& imgBw, Mat& imgLabeled){Mat imgClone = Mat(imgBw.rows + 1, imgBw.cols + 1, imgBw.type(), Scalar(0));imgBw.copyTo(imgClone(Rect(1, 1, imgBw.cols, imgBw.rows)));imgLabeled.create(imgClone.size(), imgClone.type());imgLabeled.setTo(Scalar::all(0));vector<vector<Point> > contours;vector<Vec4i> hierarchy;findContours(imgClone, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);vector<int> contoursLabel(contours.size(), 0);int numlab = 1;//标记外围轮廓for (int i = 0; i < contours.size(); ++i){if (hierarchy[i][3] >= 0)continue;for (int j = 0; j < contours[i].size(); ++j){//at(i,j) 表示第i行,第j列,与(x,y)正好相反imgLabeled.at<uchar>(contours[i][j].y, contours[i][j].x) = numlab;}contoursLabel[i] = numlab++;}//标记内轮廓for (int i = 0; i < contours.size(); ++i){if (hierarchy[i][3] < 0)continue;for (int j = 0; j < contours[i].size(); ++j){//at(i,j) 表示第i行,第j列,与(x,y)正好相反imgLabeled.at<uchar>(contours[i][j].y, contours[i][j].x) =contoursLabel[hierarchy[i][3]];}}//标记for (int i = 0; i < imgLabeled.rows; ++i){for (int j = 0; j < imgLabeled.cols; ++j){if (imgLabeled.at<uchar>(i, j) == 0 &&imgClone.at<uchar>(i,j) != 0)imgLabeled.at<uchar>(i, j) = imgLabeled.at<uchar>(i, j - 1);}}imgLabeled = imgLabeled(Rect(1, 1, imgBw.cols, imgBw.rows)).clone();}

5. 将多边形顶点按逆时针排序

Point center;bool PointCmp(const Point &a,const Point &b){if (a.x >= 0 && b.x < 0)return true;if (a.x == 0 && b.x == 0)return a.y > b.y;//向量OA和向量OB的叉积int det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);if (det < 0)return true;if (det > 0)return false;//向量OA和向量OB共线,以距离判断大小int d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y);int d2 = (b.x - center.x) * (b.x - center.y) + (b.y - center.y) * (b.y - center.y);return d1 > d2;}bool Cmp(const Point &a,const Point &b){return !PointCmp(a,b);}Point Gravity(Point *p, int n) {//返回多边形的重心double area = 0;Point center;center.x = 0;center.y = 0;for (int i = 0; i < n-1; i++) {area += (p[i].x*p[i+1].y - p[i+1].x*p[i].y)/2;center.x += (p[i].x*p[i+1].y - p[i+1].x*p[i].y) * (p[i].x + p[i+1].x);center.y += (p[i].x*p[i+1].y - p[i+1].x*p[i].y) * (p[i].y + p[i+1].y);}area += (p[n-1].x*p[0].y - p[0].x*p[n-1].y)/2;center.x += (p[n-1].x*p[0].y - p[0].x*p[n-1].y) * (p[n-1].x + p[0].x);center.y += (p[n-1].x*p[0].y - p[0].x*p[n-1].y) * (p[n-1].y + p[0].y);center.x /= 6*area;center.y /= 6*area;return center;}void ClockwiseSortPoints(Point* vPoints, int n){//计算重心center=Gravity(vPoints,n);sort(vPoints,vPoints+n,Cmp);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。