c++ 小技巧总结

本文介绍了C++中的一些常见编程技巧,包括改变控制台输出的UTF-8编码,设置当前文件索引路径,读取和写入文件,检查map中元素是否存在,替换字符串中的字符,以及高效地拼接和格式化字符串。同时,展示了如何在Linux环境中解决std::make_unique的兼容性问题。
摘要由CSDN通过智能技术生成

1:改变控制台输出的文本格式,特别是中文编码的问题,转换成UTF-8

	system("chcp 65001");

	system("cls");

2:改变当前文件索引路径(改为运行文件路径)

#include <direct.h>  //需要包含这个文件
// change current run path
	std::string rootPath = "";
#ifdef WIN32
	char* buf = _getcwd(nullptr, 0);
	if (buf) {
		rootPath = std::string(buf) + "\\";
		delete buf;
		buf = nullptr;
	}
#endif
	_chdir(rootPath.c_str());

3:c++ 读文件

	std::fstream myfile("./value.txt", std::ios::in);
	if (!myfile.is_open()) {
		std::cout << "file is open fail"<< std::endl;
	}
	std::string temp;
	while (getline(myfile, temp)) {
		std::cout << temp << std::endl;
	}
	myfile.close();

4:c++ map判断元素是否存在

//1、Count,返回1则存在,返回0则不存在
if (1 == wellInfoMap.count(key))
{
	balabala
}
//2、Find,得到的结果不是map的end则存在,否则不存在
if (wellInfoMap.end() != wellInfoMap.find(key))
{
	pilipala
}

5:数据替换,中间替换分隔符

	/**
	 * 数据转换
	 * @param data
	 * @param <T>
	 * @return
	 */
	template <typename T>
	static std::string convertTo(std::vector<T> data,std::string splidStr) {
		std::string buf;
		for (unsigned int i = 0; i < data.size(); i++) {
			buf.append(std::to_string(data[i]));
			if (i < data.size() - 1) {
				buf.append(splidStr);
			}
		}
		return buf;
	}

6:c++写的拼接字符串的函数

template <typename... Args>
std::string stringFormat(const std::string &format, Args... args)
{
	size_t size = (size_t)snprintf(NULL, 0, format.c_str(), args...) + 1;
	std::unique_ptr<char> buf(new char[size]);
	snprintf(buf.get(), size, format.c_str(), args...);
	return std::string(buf.get(), size - 1);
}

类似使用:stringFormat(“%s %s”, “hello”,“world”);

7:c++ 替换字符串

str.erase(std::remove(str.begin(), str.end(), ‘a’), str.end());

8:c++写文件

FILE* fp = fopen("out.txt","wb");
if(!fp)
	return;
fprintf(fp,"%s",value);
fclose(fp);

9:c++ vector拷贝赋值

// 这里用vector<char>拷贝string为例
std::vector<char>result;
std::string str("data");
result.assign(str.begin(),str.end());

10:如果在linux编译中遇到std::make_unique问题,可能是因为c++11为提供make_unique操作,c++14提供了该函数,所以需要做兼容

namespase utils{
#include <memory>

template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&& ... params)
{
	return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

搁浅的渔

创作不易,多多支持

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

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

打赏作者

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

抵扣说明:

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

余额充值