常用C++库及测试程序

不是特别经常使用C++,所以用一用就忘记了,每次用就得查具体用法,坑得踩好几次,故把常用的都测试通,经常看,不要总是本本族就行了。也希望能对在读的你有所帮助。

主要包括C++最常用函数库及部分封装库:包括vector,hash_set, hash_map, 文件读写,时间,字符串处理,压缩,正则表达式,redis,文件系统,日志,参数解析,base64,json处理等等,简单易用。

下载地址https://download.csdn.net/download/mj641893086/10346620

注:在centos6.2系统下测试没问题,有问题欢迎反馈。

使用方法:到test目录下,make,正常应该是可以编译的,main.cpp是各种测试,很容易看懂,后面会贴上代码,可以单独测试。在执行的时候,注意export LD_LIBRARY_PATH=../lib:$LD_LIBRARY_PATH就行。

#include "mutil/common.h"
#include "mutil/util.h"
#include "mutil/qbase64.h"
#include "mutil/qcompress.h"
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "boost/lexical_cast.hpp"
#include "boost/algorithm/string.hpp"
#include "boost/algorithm/string/regex.hpp"
#include "re2/re2.h"
#include <regex>
#include <time.h>
#include "boost/filesystem.hpp"
#include <fstream>
#include "glog/logging.h"
#include "gflags/gflags.h"
#include <omp.h>
#include "mutil/redis.h"

using namespace std;
using namespace __gnu_cxx;
using namespace rapidjson;
using namespace boost;

/*********************vector*****************/
void vector_test(){ //common.h
    vector<string> v;
    //push_back
    v.push_back("cdb");
    v.push_back("be");
    v.push_back("123");
    v.push_back("def");
    //erase
    v.erase(v.begin()+2);
    //iterator
    vector<string>::iterator it;
    for(it = v.begin();it!=v.end();it++){
        cout<<*it<<endl;
    }
    //[]
    for(int i=0;i<v.size();i++){
        cout<<v[i]<<endl;
    }
    //clear
    v.clear();
    vector<string>().swap(v); //safety clear
    cout<<"v after clear's size:"<<v.size()<<endl;
}

/*********************hash_set*****************/
void hash_set_test(){//common.h
    hash_set<string> hs;
    //insert
    hs.insert("cdb");
    hs.insert("be");
    hs.insert("123");
    hs.insert("def");
    //find
    bool flag = true;
    if(hs.find("def")==hs.end())flag = false;
    cout<<"def in hash_set:"<<flag<<endl;
    flag = true;
    if(hs.find("abc")==hs.end())flag = false;
    cout<<"abc in hash_set:"<<flag<<endl;
    //erase
    hs.erase("123");
    //iterator
    hash_set<string>::iterator it;
    for(it = hs.begin();it!=hs.end();it++){
        cout<<*it<<endl;
    }
    //clear
    hs.clear();
    hash_set<string>().swap(hs); //safety clear
    cout<<"hs after clear's size:"<<hs.size()<<endl;
}

/*********************hash_map*****************/
void hash_map_test(){//common.h
    hash_map<string,int> hm;
    //set key value
    hm["a"] = 1;
    hm["b"] = 2;
    hm["c"] = 3;
    //find
    bool flag = true;
    if(hm.find("d")==hm.end())flag = false;
    cout<<"d in hash_map:"<<flag<<endl;
    flag = true;
    if(hm.find("b")==hm.end())flag = false;
    cout<<"b in hash_map:"<<flag<<endl;
    //get value
    cout<<hm["b"]<<endl;
    cout<<hm["d"]<<endl;//return default 0 and insert an new item 'd'
    //erase
    hm.erase("b");
    //iterator
    hash_map<string,int>::iterator it;
    for(it=hm.begin();it!=hm.end();it++){
        cout<<"key:"<<it->first<<", value:"<<it->second<<endl;
    }
    //clear
    hm.clear();
    hash_map<string,int>().swap(hm);//safety clear
    cout<<"hm after clear's size:"<<hm.size()<<endl;
}

/*********************base64*****************/
void base64_test(){//qbase64.h -lmutil
    string s="abc";
    string s_b64 = qbase64_encode(s);
    cout<<"s_b64:"<<s_b64<<endl;
    s = qbase64_decode(s_b64);
    cout<<"s:"<<s<<endl;
}

/*********************qcompress*****************/
void qcompress_test(){//qcompress.h -lz -lmutil
    string s="abc";
    string s_c_b64 = qbase64_encode(qcompress(s));
    cout<<"s_c_b64:"<<s_c_b64<<endl;
    string s_origin = quncompress(qbase64_decode(s_c_b64));
    cout<<"s_origin:"<<s_origin<<endl;
}

/*********************rapidjson*****************/
//rapidjson/document.h, rapidjson/writer.h, rapidjson/stringbuffer.h
void rapidjson_test(){ 
    Document d;
    d.SetObject();//设置d为key-value型对象
    Document::AllocatorType& allocator = d.GetAllocator();
    //添加普通key-value
    d.AddMember("id","mj",allocator);
    d.AddMember("name",123,allocator);
    d.AddMember("class","xinji2",allocator);
    //添加key-数组
    Value location_array(rapidjson::kArrayType);//数组类型
    location_array.PushBack("beijing",allocator);
    location_array.PushBack("xian",allocator);
    location_array.PushBack("anhui",allocator);
    d.AddMember("location",location_array,allocator);
    //添加key-object(k-v)
    Value zimu_dic(rapidjson::kObjectType);//Object类型
    zimu_dic.AddMember("a",1,allocator);
    zimu_dic.AddMember("b",2,allocator);
    zimu_dic.AddMember("c",3,allocator);
    d.AddMember("zimu",zimu_dic,allocator);
    //json转string
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    d.Accept(writer);
    cout<<buffer.GetString()<<endl;
    //string转json
    string s = buffer.GetString();
    Document d1;
    d1.Parse<0>(s.c_str());
    if(d1.HasParseError()){
        cout<<"parse error!"<<endl;
    }
    else{
        cout<<"parse success!"<<endl;
    }
    Document::AllocatorType& allocator1 = d1.GetAllocator();
    //查询普通key
    if(d1.HasMember("name"))
        cout<<"name:"<<d1["name"].GetInt()<<endl;
    if(d1.HasMember("id"))
        cout<<"id:"<<d1["id"].GetString()<<endl;
    //修改普通key
    d1["name"].SetString("mj");
    d1["id"].SetInt(123);
    //查询array
    Value& loc_arr = d1["location"];//返回的是引用,直接修改即可
    for(int i=0;i<loc_arr.Size();i++)
        cout<<"location:"<<loc_arr[i].GetString()<<endl;
    //修改array
    loc_arr[1].SetString("xi'an");
    loc_arr.PushBack("jinzhong",allocator1);
    //查询Object(k-v)
    Value& zm_dic = d1["zimu"];//返回的是引用,直接修改即可
    Document::MemberIterator it;
    for(it = zm_dic.MemberBegin();it!=zm_dic.MemberEnd();it++){
        cout<<it->name.GetString()<<"<--->"<<it->value.GetInt()<<endl;
    }
    //修改Object(k-v)
    zm_dic["b"].SetInt(4);
    zm_dic.AddMember("d","666",allocator1);
    //删除key
    d1.RemoveMember("class");
    //输出d1
    rapidjson::StringBuffer buffer1;
    rapidjson::Writer<rapidjson::StringBuffer> writer1(buffer1);
    d1.Accept(writer1);
    cout<<buffer1.GetString()<<endl;
}

/*********************string*****************/
// boost/algorithm/string.hpp, boost/lexical_cast.hpp, boost/algorithm/string/regex.hpp
void string_test(){ 
    string s=" Hello world for you world ok! \n";
    cout<<"s:\""<<s<<"\""<<endl;
    //trim
    string s_tlc = trim_left_copy(s);
    string s_trc = trim_right_copy(s);
    string s_tc  = trim_copy(s);
    string s_tci = trim_copy_if(s,is_any_of("\n !"));
    cout<<"trim_copy_if:"<<s_tci<<endl;
    trim_right_if(s,is_any_of("\n "));//always used in python
    trim_left_if(s,is_any_of(" "));
    cout<<"after trim s:\""<<s<<"\""<<endl;
    //starts_with,ends_with
    cout<<"s starts_with \'hello\':"<<starts_with(s,"hello")<<endl;
    cout<<"s ends_with \'ok!\':"<<ends_with(s,"ok!")<<endl;
    //split
    vector<string> v;
    split(v,s,is_any_of(" "));
    for(int i=0;i<v.size();i++)
        cout<<"v["<<i<<"]:"<<v[i]<<endl;
    split_regex(v,s,boost::regex("or"));//按字符串分割,需要boost/algorithm/string/regex.hpp, -lboost_regex
    for(int i=0;i<v.size();i++)
        cout<<"v_or["<<i<<"]:"<<v[i]<<endl;
    //join
    string s_new = join(v,"**");
    cout<<"join s_new is:\""<<s_new<<"\""<<endl;
    //find,substr
    int pos = s.find("test");
    if(pos==-1)
        cout<<"not find test!"<<endl;
    pos = s.find("for");
    if(pos!=-1){
        string s_sub = s.substr(pos,s.length()-pos);
        cout<<"substring:"<<s_sub<<endl;
    }
    //replace
    string s_r = replace_all_copy(s,"or","##");
    cout<<"s_r:"<<s_r<<endl;
    //lexical_cast
    s = "123";
    int s_int = lexical_cast<int>(s);
    cout<<"s_int:"<<s_int<<endl;
}

/******************re********************/
// re2/re2.h -lre2 Makefile需要添加:RE2_CXXFLAGS?=-std=c++11 -pthread
void re_test(){ 
    //Match
    string s = "http://www.baidu.com/8686886.html?code=3";
    string reg = "http://www.baidu.com/\\d+.html";
    cout<<"PartialMatch:"<<RE2::PartialMatch(s,reg)<<endl;
    cout<<"FullMatch:"<<RE2::FullMatch(s,reg)<<endl;
    //Submatch Extraction
    string reg_s = "http://www.baidu.com/(\\d+).html";
    string id = "";
    RE2 re(reg_s);//compile before used
    RE2::PartialMatch(s,re,&id);
    cout<<"match id:"<<id<<endl;
    //C++自带regex, regex.h
    std::regex reg2(reg);
    cout<<"C++ regex_match:"<<std::regex_match(s,reg2)<<endl;//same as FullMatch
}

/******************time********************/
void time_test(){ //time.h
    //时间戳,可进行计算
    time_t t = time(NULL);
    printf("The calendar time now is %d\n",t);
    //sleep
    sleep(3);
    int id = t/30;
    cout<<id<<endl;
    //时间戳格式化
    time_t tts = 1522444662;
    struct tm* timeinfo = localtime(&tts);
    char buf[80];
    strftime(buf,sizeof(buf),"%Y-%m-%d %H:%M:%S",timeinfo);
    cout<<buf<<endl;
    //格式化时间转时间戳
    string ftime = "2018-03-31 05:17:42";
    time_t tts2 = mutil::time2tts(ftime);// mutil/util.h -lmutil
    cout<<"tts:"<<tts2<<endl;
}

/******************filesystem********************/
void file_test(){ //boost/filesystem.hpp -lboost_filesystem
    //current dir
    string cur_dir = filesystem::initial_path<filesystem::path>().string();
    cout<<"cur_dir:"<<cur_dir<<endl;
    filesystem::path cur_path = filesystem::initial_path<filesystem::path>();
    //parent dir
    filesystem::path parent_dir = cur_path.parent_path();
    cout<<"parent_dir:"<<parent_dir.string()<<endl;
    //filename,stem(前缀),extension(扩展),file_size
    string cpp_file = cur_dir+"/test.cpp";
    filesystem::path cpp_path(cpp_file);
    string filename = cpp_path.filename().string();
    cout<<"filename:"<<filename<<endl;
    string stem = cpp_path.stem().string();
    string extension = cpp_path.extension().string();
    cout<<"stem:"<<stem<<endl;
    cout<<"extension:"<<extension<<endl;
    int file_size = filesystem::file_size(cpp_path);
    cout<<"file_size:"<<file_size<<endl;
    //last_write_time
    int last_write_time = filesystem::last_write_time(cpp_path);
    cout<<"last_write_time:"<<last_write_time<<endl;
    if(time(NULL)-last_write_time>10)
        cout<<"modified 10s ago"<<endl;
    //exists
    string t_file = cur_dir+"/t";
    cout<<t_file<<" exists:"<<filesystem::exists(t_file)<<endl;
    //file_stat:is_regular_file,is_directory,is_symlink
    cout<<cpp_path<<" is_regular_file:"<<filesystem::is_regular_file(cpp_path)<<endl;
    cout<<cpp_path<<" is_directory:"<<filesystem::is_directory(cpp_path)<<endl;
    string mlib = cur_dir+"/mlib";
    cout<<mlib<<" is_symlink:"<<filesystem::is_symlink(mlib)<<endl;
    //remove,rename,copy_file
    if(filesystem::exists(t_file))
        filesystem::remove(t_file);
    string bak_path = cpp_file+".bak";
    string rename_path = cpp_file+".rename";
    if(filesystem::exists(bak_path))
        filesystem::remove(bak_path);
    if(filesystem::exists(rename_path))
        filesystem::remove(rename_path);
    filesystem::copy_file(cpp_file,bak_path);
    filesystem::rename(bak_path,rename_path);
    filesystem::remove(rename_path);
    //创建目录
    string new_dir = cur_dir+"/new_dir";
    if(!filesystem::exists(new_dir))
        filesystem::create_directories(new_dir);
    filesystem::remove(new_dir);
    //遍历目录
    for(filesystem::recursive_directory_iterator it(cur_dir);it!=filesystem::recursive_directory_iterator();it++){
        cout<<"dir_file:"<<it->path()<<endl;
    }
}

/******************read-write********************/
void read_write_test(){
    string cur_dir = filesystem::initial_path<filesystem::path>().string();
    string fpath = cur_dir+"/a.txt";
    string fbpath = cur_dir+"/a.bin";
    /****C:<stdio.h>****/
    //write
    FILE* fp = fopen(fpath.c_str(),"w+");
    fputs("sss\n",fp);
    fputs("aaa",fp);
    fprintf(fp,"%s\t%d\t%s\n","bbb",123,"ccc");
    fprintf(fp,"ddd");
    fclose(fp);
    //read
    fp = fopen(fpath.c_str(),"r");
    int max_line_len = 1024;
    char buf[max_line_len];
    while(!feof(fp)){
        fgets(buf,max_line_len,fp);//遇到\n或者字符数为max_line_len-1则读行完毕
        string s = buf;
        s = trim_right_copy_if(s,is_any_of("\n"));//读到\n会在结尾
        cout<<"read_content:\""<<s<<"\""<<endl;
    }
    fclose(fp);
    //write-binary
    fp = fopen(fbpath.c_str(),"wb");
    fprintf(fp,"%s\t%d\n","xiaoma",123);
    int a = 456;
    int b[3] = {56,78,910};
    fwrite(&a,sizeof(int),1,fp);
    fwrite(&b,sizeof(int),sizeof(b)/sizeof(int),fp);
    fclose(fp);
    //read-binary
    fp = fopen(fbpath.c_str(),"rb");
    char name[100];
    int id;
    fscanf(fp,"%s\t%d\n",&name,&id);
    cout<<"name:"<<name<<endl;
    cout<<"id:"<<id<<endl;
    int c[4];
    fread(&c,sizeof(int),sizeof(c)/sizeof(int),fp);
    for(int i=0;i<4;i++)
        printf("c[%d]:%d\n",i,c[i]);
    fclose(fp);
    /****C++:<fstream>****/
    //write
    fstream f(fpath.c_str(),ios::out);
    f<<"aaa"<<endl;
    f<<"bbb"<<endl;
    f<<"ccc"<<endl;
    f.close();
    //read
    f.open(fpath.c_str(),ios::in);
    string s;
    while(getline(f,s)){
        cout<<"c++ read:"<<s<<endl;
    }
    f.close();
    //write-binary
    ofstream fb(fbpath.c_str(),ios::binary);
    int p[3] = {33,44,55};
    double q[4] = {3.3,4.4,5.5,6.6};
    fb.write((char*)p,sizeof(p));
    fb.write((char*)q,sizeof(q));
    fb.close();
    //read-binary
    ifstream fbi(fbpath.c_str(),ios::binary);
    int pi[3];
    double qi[4];
    fbi.read((char*)pi,sizeof(pi));
    fbi.read((char*)qi,sizeof(qi));
    for(int i=0;i<3;i++){
        printf("p[%d]:%d\n",i,pi[i]);
    }
    for(int i=0;i<4;i++){
        printf("q[%d]:%lf\n",i,qi[i]);
    }
    fbi.close();
}

/******************glog********************/
void glog_test(){ // glog/logging.h -lglog
    //init
    google::InitGoogleLogging("test");//日志文件前缀
    FLAGS_log_dir = "./log";          //设置日志目录
    FLAGS_alsologtostderr = true;     //设置日志消息除了日志文件之外是否去标准输出
    //FLAGS_logtostderr = true;         //设置日志消息是否转到标准输出而不是日志文件
    FLAGS_colorlogtostderr = true;    //设置记录到标准输出的颜色消息(如果终端支持)
    //log
    LOG(INFO)<<"info test";
    int a = 11;
    LOG(ERROR)<<"error test";
    LOG(WARNING)<<"warning test";
    //LOG(FATAL)<<"fatal test";      //输出一个Fatal日志,这是最严重的日志并且输出之后会中止程序
    LOG_IF(ERROR,a%2!=0)<<"a is jishu";
    CHECK(a>10)<<"if a<=10 will Print this log(fatal), the program will break";
    //close
    google::ShutdownGoogleLogging();//程序完结时必须有,否则会内存泄露
}

/******************gflags********************/
// gflags/gflags.h -lgflags
//定义参数
DEFINE_string(ip,"127.0.0.1","your IP~");
DEFINE_int32(port,9090,"your port~");
DEFINE_bool(mflag,true,"mflag~");//-nomflag表示false,-mflag表示true
DEFINE_double(ratio,1.05,"retry connect ratio~");

/******************OpenMP********************/
void omp_test(){ // omp.h -fopenmp
    omp_set_num_threads(4);
    #pragma omp parallel //后面括号模块是并行的内容  
    {  
        sleep(1);
        #pragma omp critical //紧跟的一行语句会上锁,用于变量同步操作
        cout << "Hello" << ", I am Thread " << omp_get_thread_num() << endl;  
        #pragma omp barrier  //路障:等待所有执行完才能执行
        #pragma omp for      //for循环并行
        for(int i=0;i<10;i++){
            cout<<"out:"<<i<<", Thread-"<< omp_get_thread_num() << endl;
        }
    }
}

/******************redis********************/
void redis_test(){ // mutil/redis.h -lmutil -lhiredis
    //connect
    mutil::Redis *rds = new mutil::Redis();
    bool conn_flag = rds->connect_redis("your.host.name",8888,1,"password");
    if(!conn_flag)
        cout<<"connect error~"<<endl;
    else
        cout<<"connect ok~"<<endl;
    //get
    string value;
    if(rds->get("key",value))
        cout<<"value:"<<value<<endl;
    //set
    rds->set("redis","wawawa");
    rds->get("redis",value);
    cout<<"value:"<<value<<endl;
    delete rds;
}

int main(int argc,char* argv[]){
    vector_test();
    hash_set_test();
    hash_map_test();
    base64_test();
    qcompress_test();
    rapidjson_test();
    string_test();
    re_test();
    time_test();
    file_test();
    read_write_test();
    glog_test();
    //gflags_test
        //初始化
        gflags::SetVersionString("1.0.0");//--version的时候会显示
        string usage_str = "Usage:";
        usage_str += argv[0];
        gflags::SetUsageMessage(usage_str);
        if(argc<2){
            gflags::ShowUsageWithFlagsRestrict(argv[0], "test");//注意:第二个参数是限制的model_name
            return 0;
        }
        //参数解析
        gflags::ParseCommandLineFlags(&argc,&argv,true);//true表示不保留定义的flags
        cout<<"ip:"<<FLAGS_ip<<endl;
        cout<<"port:"<<FLAGS_port<<endl;
        cout<<"mflag:"<<FLAGS_mflag<<endl;
        cout<<"ratio:"<<FLAGS_ratio<<endl;
    omp_test();
    redis_test();
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值