c++ 工具函数

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转的函数原型,其他类似
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值