C++常用技巧
收集一些在工作中需要用到的C++知识,一方面是为了学习C++,一方面为了积累知识
1. 判断路径是否存在
#include <windows.h>
#include <direct.h>
bool dirExists(const std::string& dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in.c_str());
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
// 不存在路径就创建
if (!dirExists(output_normal_val_path))
{
std::cout << output_normal_val_path << "not exist \n";
_mkdir(output_normal_val_path.c_str());
std::cout << "mkdir : " << output_normal_val_path << std::endl;
//return 0;
}
2. 获得文件路径中文件名
std::string GetPathOrURLShortName(std::string strFullName)
{
if (strFullName.empty())
{
return "";
}
std::string::size_type iPos = strFullName.find_last_of('/') + 1;
return strFullName.substr(iPos, strFullName.length() - iPos);
}
std::string get_frameIndex(std::string path, std::string text="tracker")
{
if (path.empty())
{
return "";
}
std::string::size_type iPos = path.find_last_of('/') + 1;
std::string file_name = path.substr(iPos, path.length() - iPos);
return file_name.substr(text.length(), 2);
}
3. string 与 int之间的相互转化
string --> int : i = atoi(s.c_str())
int --> string : s = std::to_string(i)
string --> char : char c = s[0]
char -->string : s = string(1, c)
4. C++ 读取json文件中数据
#include <json/json.h>
vlog_template.vec_lens.clear();
Json::CharReaderBuilder builder;
builder["collectComments"] = false;
Json::Value jsonRoot;
std::cout << "json file :" << json_path << std::endl;
std::ifstream input(json_path, std::ios::binary);
if (!input.is_open())
{
std::cout << "File Openned failure\n";
return -1;
}
JSONCPP_STRING errs;
if (!parseFromStream(builder, input, &jsonRoot, &errs)) //从ifs中读取数据到jsonRoot
{
std::cout << "Json data read Failure\n";
return -2;
}
//std::string jsonStr = jsonRoot.toStyledString(); //json字符串
vlog_template.versoin = jsonRoot["version"].asString();
Json::Value timeRoot = jsonRoot["times"];
vlog_template.vec_time.clear();
for (auto iter = timeRoot.begin(); iter != timeRoot.end(); iter++)
{
vlog_template.vec_time.push_back((*iter).asFloat());
}
vlog_template.vec_lens.clear();
Json::Value logicRoot = jsonRoot["logic"];
for (auto logic_id = 0; logic_id < logicRoot.size(); logic_id++)
{
LensLogic lens_logic;
lens_logic.lens_name = logicRoot[logic_id]["lens_name"].asString();
lens_logic.lens_templ = logicRoot[logic_id]["template"].asString();
vlog_template.vec_lens.push_back(lens_logic);
}
5. 读取文件:中文乱码
string UTF8ToGB(const char* str)
{
string result;
WCHAR *strSrc;
LPSTR szRes;
//获得临时变量的大小
int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i + 1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
//获得临时变量的大小
i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
szRes = new CHAR[i + 1];
WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szRes;
delete[]strSrc;
delete[]szRes;
return result;
}
std::string output_path ="//192.168.2.59/sdc/datasets/panorama_tripod/";
ifstream ifs2("D:/JLCAI/insta360/myself/ML/code/tensorflow/cubeMap/1.txt");
std::vector<std::string> imgs_path;
std::string temp;
cv::Mat out;
int i = 0;
while (std::getline(ifs2, temp))
{
string str = UTF8ToGB(temp.c_str()).c_str();
//对每一行进行操作。
cout << str << "\n";
cv::Mat img = cv::imread(str);
int width = img.cols;
int height = img.rows;
if (width == height)
{
out = img(cv::Rect(0, 0, width, height / 2));
}
else if (width == height * 2)
{
img.copyTo(out);
}
cv::imwrite(output_path + to_string(i) + ".jpg", out);
i++;
}
6. 分割字符串
std::vector<std::string> splitWithStl(const std::string &str, const std::string &pattern)
{
std::vector<std::string> resVec;
if ("" == str)
{
return resVec;
}
//方便截取最后一段数据
std::string strs = str + pattern;
size_t pos = strs.find(pattern);
size_t size = strs.size();
while (pos != std::string::npos)
{
std::string x = strs.substr(0, pos);
resVec.push_back(x);
strs = strs.substr(pos + 1, size);
pos = strs.find(pattern);
}
return resVec;
}
示例:
std::string test = "This is test code";
std::vector<std::string> vec = splitWithStl(test, " ");
for(int i=0; i < vec.size(); i++)
{
std::cout << vec[i]<<std::endl;
}
result:
This
is
test
code
7. C++计算运算时长
方法1: time
#include <ctime> // <time.h>
const clock_t start_time = clocl();
...
float cast_time = float(clock() - start_time)/ CLOCKS_PER_SEC ; //以秒为单位
备注:CLOCKS_PER_SEC 用来表示一秒钟会有多少个时钟计时单元
方法2: