c++ 工具函数.md
两值互换swap()
位于,实现两个同类型的值,值相互交换。
函数原型:
template<typename T>
inline void swap(T& a, T& b);
挑选最小值和最大值
操作 | 效果 |
---|---|
min(a,b) | 返回a和b之间的最小值,以<进行比较,返回引用 |
min(a,b,cmp) | 返回a和b之间的最小值,以cmp进行比较,返回引用 |
min(initlist) | 返回initlist中的最小值,以<进行比较,返回拷贝 |
min(initlist,cmp | 返回initlist中的最小值,以cmp进行比较,返回拷贝 |
另外max()函数和minmax()函数用法完全一致,
其中minmax()返回一个pair<>,其中的first是最小值,second是最大值
计算两段代码的执行时间
cpp标准库计时函数
示例:
#include <chrono>
using namespace std;
chrono::steady_clock::time_point tp1=chrono::steady_clock::now();
//执行一堆语句
auto diff=chrono::steady_clock::now()-tp1;
double tracktime=chrono::duration_cast< chrono::duration<double> >(diff).count();
//上一句也可以写成:
auto sec=chrono::duration_cast<chrono::seconds>(diff).count();
//然后打印这个秒即可,当然也可以改成 minutes或者hours
类型转换函数
string转int,float,double,usignedlong,longdouble,longint等
#include <string>
int stoi (const string& str, size_t* idx = 0, int base = 10); //函数原型:转为int
float stof(const string& str, size_t& idx=0); //转为float
double stod (const string& str, size_t* idx = 0); //转为double
unsigned long stoul(const string& str, size_t* idx = 0, int base = 10);
long double stold(const string& str, size_t* idx = 0);
long stol (const string& str, size_t* idx = 0, int base = 10);
C型字符串转int,float,double,longint,
#include <stdlib.h>
int atoi(char*); //输入为C型的字符串指针
float strtof (const char* str, char** endptr); /* strtof */
double atof (const char* str);
long int atol ( const char * str );
string转C型字符串
string str; //定义string类型字符串对象
char c_string[20]; //定义C型字符串数组
c_string=str.c_str(); //将string对象转换为C型字符串数组并存入c_string数组
int,long,long long,unsigned,unsigned long,unsigned long long,float,double,long double转换为string
string to_string(int a);//int转的函数原型,其他类似