C++ 代码小工具(壹)
1、vector 二维数组的转置
代码:
template<typename T>
vector<vector<T> > transpose(vector<vector<T> >& matrix)
{
vector<vector<T>>v(matrix[0].size(), vector<T>());
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[0].size(); j++)
{
v[j].push_back(matrix[i][j]);
}
}
return v;
}
注释:
参数 matrix: 输入二维 vector 数组
返回:转置后的二维 vector 数组
运行结果:
2、文件保存
code
1、宏定义
#define DEBUG 0 // 开关
/*
* PRINTF调试信息:
* 使用:PRINTF(),打印调试log
* // 这个宏是用来打印错误信息的,其中__FILE__、__FUNCTION__、__LINE__是编译器提供的宏,
* 分别可以用来打印文件名、函数名、和行号
*/
#ifdef DEBUG
#define MY_INFORM(format, ...) printf("INFO[%d]: ",__LINE__);printf(format"\r\n",##__VA_ARGS__)
#define MY_ERRO(erro, ...) printf("ERROR[%d]: %s/%s \r\n",__LINE__,__FILE__,__FUNCTION__); printf(erro"\r\n",##__VA_ARGS__); exit(0)
#else
#define MY_INFORM(format, ...)
#define MY_ERRO(erro, ...)
#endif
#define PATHNAME 0
#ifdef PATHNAME
const string PATH = "/home/lhl/Samplering/gmm/data/";
#else
const string PATH = "./";
#endif
2、写文件
const string FILE_NAME = "data";
const string FILE_TYPE = ".txt";
template<typename T>
void writefile(int count,vector<T> target)
{
vector<T> TARGET(target);
string COUNT = static_cast<string>(to_string(count));
string FILE = PATH + FILE_NAME + COUNT + FILE_TYPE;
MY_INFORM("File name is %s",FILE.c_str());
fstream FILEx;
FILEx.open(FILE,ios::out);
if (!FILEx.is_open())
{
MY_ERRO("The file %s can't be open!",FILE.c_str());
}
for (auto i = TARGET.begin(); i < TARGET.end(); i++)
{
FILEx << *i << " ";
}
FILEx << endl;
FILEx.close();
}
3、main
int main(int argc, char const *argv[])
{
int count = 0;
vector<string> my_TEXT = {"my","name","is","l","Yoos"};
MY_INFORM("Save File!");
writefile(1,my_TEXT);
MY_INFORM("Save successed!");
return 0;
}
运行结果:
|