小函数

来源:互联网 发布:朴敏英为什么不火 知乎 编辑:程序博客网 时间:2024/05/17 01:50
有这样的函数const std::string *my_names(){static const std::string priority_names[10] ={"FATAL","ALERT","CRIT","ERROR","WARN","NOTICE","INFO","DEBUG","NOTSET","UNKNOWN"};return priority_names;}这样调用的 my_names()[0],my_names()[1],my_names()[2];
/*!********************************************************************************   @brief 枚举类型的宏定义********************************************************************************/#define DECLARE_ENUM(E) \    struct E \    { \    public: \        E(int value = 0) : _value((__Enum)value) \        { \        } \        E& operator=(int value) \        { \            this->_value = (__Enum)value; \            return *this; \        } \        operator int() const  \        { \            return this->_value; \        } \    \        enum __Enum \        {#define END_ENUM \        }; \    \    private: \        __Enum _value; \    };/*!********************************************************************************   @brief  常用函数********************************************************************************/class CCommon{public:    CCommon();    ~CCommon();public:    /**    * @brief    将字符串转为大写    * @param    [IN] [OUT] 字符串    * @return   [OUT] 大写字符串    */    static std::string ToUpper(std::string &s);    /**    * @brief    将字符串转为小写    * @param    [IN] [OUT] 字符串    * @return   [OUT] 小写字符串    */    static std::string ToLower(std::string &s);    /**    * @brief    去除字符串空白符    * @param    要去除空白符的字符串("\r\n\t\x20")    * @return   去除空白符后的字符串    */    static std::string Trim(const std::string &str);    /**    * @brief    去除字符串左边空白符    * @param    要去除空白符的字符串    * @return   去除空白符后的字符串    */    static std::string TrimLeft(const std::string &s);    /**    * @brief    去除字符串右边空白符    * @param    要去除空白符的字符串    * @return   去除空白符后的字符串    */    static std::string TrimRight(const std::string &s);    /**    * @brief    CreateDir 创建多级目录    * @param    pDirpath [IN] 目录路径    * @return   int32_t [OUT] 0--成功,其他--失败    */    static int32_t CreateDir(const char * pDirpath);    /**    * @brief    把字符串根据分隔符sep分解,放到vector中    * @param    [IN]  s 欲分解字符串    * @param    [OUT] v 存放地方    * @param    [IN]  sep 分隔符    * @return   无    */    static void ListToVector(const char *s, std::vector<std::string>& v, int sep);    static void ListToVector(std::string s, std::vector<std::string>& v, const std::string sep);    static void ListToVector(std::string s, std::vector<std::string>& v, const char* sep);};/*!********************************************************************************   @brief 时间类,获取时间等操作********************************************************************************/class COsTime{public:    COsTime();    ~COsTime();public:    /**    * @brief    获取现在时间  格式为:YYYY-MM-DD HH24:MM:SS    * @param    无    * @return   格式为YYYY-MM-DD HH24:MM:SS的字符串    */    static std::string now();    /**    * @brief    时间格式化    * @param    [IN]    format 格式输入    * @return   [OUT]   格式化后字符串    */    static std::string Format(const char* format);    /**    * @brief    获取现在时间  格式为:YYYYMMDDHH24MMSS    * @param    无    * @return   格式为YYYYMMDDHH24MMSS的字符串    */    static std::string GetCurrentTime();    static std::string GetYear();    static std::string GetMonth();    static std::string GetWeekDay();};


 

/*!********************************************************************************   @brief 常用函数********************************************************************************/CCommon::CCommon(){}CCommon::~CCommon(){}string CCommon::ToUpper(string& s){    if (s.empty())        return s;    for (string::iterator it=s.begin(); it!=s.end(); ++it)    {        if (isalpha(*it))            *it = toupper(*it);    }    return s;}string CCommon::ToLower(string& s){    if (s.empty())        return s;    for (string::iterator it=s.begin(); it!=s.end(); ++it)    {        if (isalpha(*it))            *it = tolower(*it);    }    return s;}string CCommon::Trim(const string& str){    static const char* blank = "\r\n\t\x20";// \f\v    if (str.empty())        return str;    string::size_type a = str.find_first_not_of(blank);    string::size_type b = str.find_last_not_of(blank);    return string(str,a,b-a+1);}string CCommon::TrimLeft(const string &s){    string::const_iterator it;    if (s.empty())        return s;    for (it = s.begin(); it != s.end(); ++it)    {        if (!isspace(*it))            break;    }    return string(it,s.end());}string CCommon::TrimRight(const string &s){    string::difference_type dt;    string::const_reverse_iterator it;    if (s.empty())        return s;    for (it = s.rbegin(); it != s.rend(); ++it)    {        if (!isspace(*it))            break;    }    dt = s.rend() - it;    return string(s.begin(),s.begin() + dt);}int32_t CCommon::CreateDir(const char * pDirpath){    assert(NULL != pDirpath);    int32_t nRet = 0;    char * p = new char[strlen(pDirpath)+1];//char * p = strdup(pDirpath);    memset(p,0x00,strlen(pDirpath)+1);    memcpy(p,pDirpath,strlen(pDirpath));    int32_t length = strlen(p);    for (int32_t i=0;i<length;++i){        if (i == 0 && (p[0] == '\\' || p[i] == '/'))//根目录不要创建            continue;        if (p[i] == '\\' || p[i] == '/'){            p[i] = '\0';            nRet = access(p,0);//不存在,则创建            if (0 != nRet){                nRet = mkdir(p,0777);                if (0 != nRet)                    return nRet;            }            p[i] = '/';        }    }    nRet = access(p,0);    if (0 != nRet)        nRet = mkdir(p,0777);    delete [] p;//free(p);    return nRet;}void CCommon::ListToVector(const char* s, std::vector<string>& v, int sep){    assert(NULL != s);    char *index = NULL;    char *pos = NULL;    char *pCopy = new char[strlen(s)+1];    memset(pCopy,0x00,strlen(s)+1);    char *pBuf = new char[strlen(s)+1];    memset(pBuf,0x00,strlen(s)+1);    memcpy(pBuf,s,strlen(s));    pos = pBuf;    while(NULL != (index = strchr(pos,sep)))    {        memset(pCopy,0x00,strlen(s)+1);        strncpy(pCopy,pos,index-pos);        string str(pCopy);        v.push_back(str);        pos = index+1;    }    if (NULL == index)    {        memset(pCopy,0x00,strlen(s)+1);        strcpy(pCopy,pos);        string str(pCopy);        v.push_back(str);    }    delete [] pBuf;    delete [] pCopy;}void CCommon::ListToVector(string s, std::vector<string>& v, const string sep){    string::size_type nIndex = 0;    string::size_type nPos = 0;    v.clear();    while(string::npos != (nIndex=s.find(sep,nPos)))    {        string m = s.substr(nPos,nIndex-nPos);        v.push_back(m);        nPos = nIndex+1;    }}void CCommon::ListToVector(string s, std::vector<string>& v, const char* sep){    v.clear();    char* buffer = new char[s.length() + 1];    memcpy(buffer, s.c_str(), s.length());    buffer[s.length()] = 0;    char* token = strtok(buffer, sep);    while (token)    {        string sToken = token;        v.push_back(sToken);        token = strtok(NULL, sep);    }    delete [] buffer;}/*!********************************************************************************   @brief 时间类********************************************************************************/COsTime::COsTime(){}COsTime::~COsTime(){}string COsTime::now(){    const char * format = "%Y-%m-%d %H:%M:%S";    return Format(format);}string COsTime::Format(const char* format){    string s;    time_t lVal;tm *plocaltime = NULL;char buffer[128] = {0x00};time(&lVal);    if ((plocaltime = localtime(&lVal)) != 0 )    if (strftime(buffer, 128, format, plocaltime) > 0)            s = buffer;return s;}string COsTime::GetCurrentTime(){    const char * format = "%Y%m%d%H%M%S";    return Format(format);}std::string COsTime::GetYear(){    const char * format = "%Y";    return Format(format);}std::string COsTime::GetMonth(){    const char * format = "%m";    return Format(format);}std::string COsTime::GetWeekDay(){    const char * format = "%A";    return Format(format);}
#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "sample.h"using namespace std;using namespace lpublic;DECLARE_ENUM(COLOR)    RED     = 3001,    BLACK   = 3002,    BLUE    = 3003END_ENUMstruct tagStudent{    int32_t id;    std::string name;    std::string address;    tagStudent()    {        id = 0;    }    tagStudent& operator=(const tagStudent& other)    {        if (this == &other)            return *this;        id = other.id;        name = other.name;        address = other.address;        return *this;    }    void print()    {        cout<<"ID:"<<id<<"  NAME:"<<name<<" ADDRESS:"<<address<<endl;    }};template struct my_minus{    _Result operator()(const _Tp& __x, const _Tp1& __y) const    {        return __x - __y;    }};void work(tagStudent* &pTagStu){    tagStudent *pTmpTag = new(std::nothrow) tagStudent;    pTmpTag->id = int(1010);    pTmpTag->name = std::string("lsp");    pTmpTag->address = std::string("xiamen");    pTagStu = pTmpTag;    pTagStu->print();}class Base{public:    virtual ~Base()    {        cout<<"~Base"<<endl;    }};class Derived:public Base{public:    virtual ~Derived()    {        cout<<"~Derived"<<endl;    }};#if 1  //函数 sort uniqueint main(int argc,char * argv[]){    ostream_iterator out_iter(cout,"\n");    istream_iterator in_iter(cin),eof;    vector vInt;    while(in_iter!=eof)    {        //*out_iter++ = *in_iter++;        vInt.push_back(*in_iter++);    }    for (vector::size_type i=0;i!=vInt.size();++i)    {        cout<<vInt[i]<<" ";    }    cout<<'\n';    const string szArray[10] = {"fox","red","red","blue","grep","blue","hello","hello","world","xml"};    vector vArray;    copy(szArray,szArray+10,back_inserter(vArray));#if 0    vector vArray(10);//vArray.resize(10);    copy(szArray,szArray+10,vArray.begin());#endif    for (vector::size_type i=0;i!=vArray.size();++i)    {        cout<<vArray[i]<<" ";    }    cout<<'\n';#if 0    for (int i=0;i!=10;++i)        vArray.push_back(szArray[i]);#endif    sort(vArray.begin(),vArray.end());    for (vector::size_type i=0;i!=vArray.size();++i)    {        cout<<vArray[i]<<" ";    }    cout<<'\n';    vector::iterator end_unique = unique(vArray.begin(),vArray.end());    for (vector::size_type i=0;i!=vArray.size();++i)    {        cout<<vArray[i]<< " ";    }    cout<<'\n';    vArray.erase(end_unique,vArray.end());    for (vector::size_type i=0;i!=vArray.size();++i)    {        cout<<vArray[i]<< " ";    }    cout<<'\n';    list lfront;    copy(vArray.begin(),vArray.end(),front_inserter(lfront));    for (list::iterator it=lfront.begin();it!=lfront.end();++it)    {        cout<<*it<<" ";    }    cout<<'\n';    return 0;}#endif // 1#if 0int main(int argc,char* argv[]){    string ifile("test.txt");    char str[1024];    ifstream infile(ifile.c_str());    while(!infile.eof())    {        infile.getline(str,1024,'\n');        cout<< str << endl;    }    return 0;}#endif#if 0class Token{public:    Token()    {        memset(val.cval,0x00,128);    }public:    enum TokenKind {INT,CHAR,DBL};    TokenKind tok;    union    {        char    cval[128];        int     ival;        double  dval;    } val;};int main(int argc, char* argv[]){    Token token;    token.tok = Token::DBL;    switch (token.tok)    {    case Token::INT:        token.val.ival = 12;        break;    case Token::CHAR:        strcpy(token.val.cval,"icool");        break;    case Token::DBL:        token.val.dval = 3.1415926;        break;    }    printf("COLOR::BLOCK = %d\n",COLOR::BLACK);    printf("token.cval = %0.7f\n",token.val.dval);    printf("token.cval = %d\n",sizeof(token.val));    my_minus jk;    printf("jk(10,40) = %d\n",jk(10,40));//    char szBlank[128];//    memset(szBlank,0x20,sizeof(szBlank));//    szBlank[sizeof(szBlank)-1] = 0x00;//    fprintf(fp,"%s",szBlank);//    printf("pos = %ld\n",ftell(fp));//    fprintf(fp,"\n");//    for (int i=1;i<10000;++i)//    {//        fprintf(fp,"第%05d行 www.huawei.com/%d.html\n",i,i);//    }//    long pos = ftell(fp);//    printf("pos = %ld,sizeof(\"\\n\")=%d\n",pos,sizeof("\n"));//    fseek(fp,0L,SEEK_SET);////    fprintf(fp,"总共{count}记录");//    fseek(fp,0L,SEEK_END);//    printf("total size = %ld\n",ftell(fp));////    fprintf(fp,"文件大小为:%ld 字节\n",ftell(fp));    return 0;}#endif#if 0int main(int argc, char *argv[]){    map mapStudent;    typedef map MAP;    mapStudent.insert(pair(1,"student_one"));    mapStudent.insert(pair(1,"student_one_1"));    mapStudent.insert(map::value_type(2,"student_two"));    mapStudent.insert(map::value_type(3,"student_three"));    mapStudent.insert(pair(4,"student_four"));    if (mapStudent.count(4) == 1)        cout << "key = 4 is exist!" << endl;    for (MAP::size_type i=1; i <= mapStudent.size(); ++i)    {        cout << mapStudent[i] << endl;    }    cout << "MAPSTUDENT SIZE: " << mapStudent.size() << endl;    for (map::iterator iter = mapStudent.begin(); iter != mapStudent.end(); ++iter)    {        cout << iter->first << "<----->" <second << endl;    }    map::key_compare comp = mapStudent.key_comp();    return 0;}#endif#if 0int main(int argc,char* agrv[]){    cout << COsTime::now() << endl;    cout << COsTime::GetYear() << endl;    cout << COsTime::GetMonth() << endl;    cout << COsTime::GetWeekDay() << endl;    cout << COsTime::GetCurrentTime() << endl;    cout << COsTime::Format("%Y-%m-%d %H:%M:%S") << endl;    string sys = "  hello,i am michelia haha  ";    sys = CCommon::TrimLeft(CCommon::ToUpper(sys));    cout << "sys = " << sys << endl;    sys = CCommon::TrimRight(CCommon::ToLower(sys));    printf("sys = %s.\n",sys.c_str());    std::string s = "c,c++,java,c#,python,js,lua,ruby";    char szBuf[128] = "";    char szOutBuffer[1024] = "";    memset(szBuf,0x00,sizeof(szBuf));    memset(szOutBuffer,0x00,sizeof(szOutBuffer));    strcpy(szBuf,"c,c++,java,c#,python,js,lua,ruby,DONE");    printf("szBuf:%s\n",szBuf);    vector vec;    std::string strOut;    string ll(szBuf);    CCommon::ListToVector(CCommon::ToUpper(ll).c_str(),vec,',');    for(vector::size_type i=0; i!=vec.size(); ++i)    {        strcat(szOutBuffer,"{");        strcat(szOutBuffer,vec[i].c_str());        strcat(szOutBuffer,"}");        strOut += "[";        strOut += vec[i].c_str();        strOut += "]";    }    cout << szOutBuffer << endl;    cout << strOut << endl;    return 1;}#endif#if 0int main(){    union u    {        char cc;        double jj;    };    struct tg1    {        int i;        u g;        short j;        char c;    };    tg1 A;    A.i = 257;    A.g.jj = 9.9;    A.j = 2;    A.c = 'c';    cout<<sizeof(u)<print();    if (pTagStu)    {        delete pTagStu;        pTagStu = NULL;    }    assert(pTagStu!=NULL);    return 1;}#endif#if 0void build_2d_array(int file_count , int dict_size , char ***p) ;void print_array(int m , int n , char**p);int main(){    int a= 5 ;    int b = 20 ;    char **v=NULL;    build_2d_array(a,b,&v) ;    print_array(a,b,v) ;    return 0 ;}void build_2d_array(int file_count , int dict_size , char ***array){    int i,j ;    *array = (char**)malloc(file_count*sizeof(char*)) ;    for(i=0 ; i< file_count ; i++)    {        *(*array+i) = (char*)malloc(dict_size*sizeof(char));    }    for (i=0; i<file_count; i++)    {        for(j=0 ; j<dict_size ; j++)            *(*(*array+i)+j) = '1' ;    }}void print_array(int m , int n , char **p){    int i,j;    assert(NULL != p);    for(i=0 ; i< m ; i++)    {        printf("element[%d]:",i);        for(j=0 ; j< n; j++)            printf("%c",(char)*(*(p+i)+j));        printf("\n");    }    for(i=0 ; i<m ; i++)        free(*(p+i)) ;    free(p);}#endif#if 0int32_t main(int32_t argc, char **argv){    vector vecStr;    const string strPath("/app/ibas85/ib85dev/src/csrc/liangsp/sample");    string strSubPath = strPath.substr(strPath.find(string("/"))+1);    cout << strSubPath << endl;    string str1 = strSubPath.substr(0,strSubPath.find('/'));    string str2 = strPath.substr(0,strPath.find('/'));    cout << "str1:" << str1 << endl;    cout << "str2:" << str2 << endl;    /////////////////////////////////////////////////////////////////////////////    tagStudent stStudent;    stStudent.id = 127336;    stStudent.name = string("xiaosha");    stStudent.address = string("Xiamen Zhenzhuwan");    tagStudent *ptr = new(std::nothrow) tagStudent();    if (NULL == ptr)    {        cout << "memory new failed!" << endl;    }    //memcpy(ptr,&stStudent,sizeof(tagStudent));    *ptr = stStudent;    cout << ptr->id << " : " << ptr->name << " : " << ptr->address << endl;    if (ptr)        delete ptr;    //assert(ptr == NULL);    string s = string("Xiamen Zhenzhuwan {sheng}");    string::size_type npos = s.find(string("{sheng}"));    cout << "NPOS = " << npos << endl;    s.replace(s.find(string("{sheng}")),string("{sheng}").length(),"Fujian");//    string s;//    getline(cin,s);    cout << s.c_str() << "------" << s.data() << endl;    for (string::size_type i=0; i!=s.size(); ++i)        cout<< s[i] << "-";    cout << endl;    for (string::const_iterator iter = s.begin(); iter != s.end(); ++iter)        cout << *iter << "\" ";    cout << endl;    for (string::reverse_iterator iter = s.rbegin(); iter != s.rend(); ++iter)        cout << *iter << "#";    cout << endl;    /////////////////////////////////////////////////////////////    time_t ltime = time(0);    cout << ltime << endl;    tm *localtm = localtime(<ime);    cout << mktime(localtm) << endl;    char sztime[64] = {0x00};    strftime(sztime,sizeof(sztime),"%Y-%m-%d %H:%M:%S",localtm);    cout << sztime << endl;    /////////////////////////////////////////////////////////////    return 0;}#endif#if 0void simple_va_fun(int i, ...){    va_list arg_ptr;    int j=0;    va_start(arg_ptr, i);    j=va_arg(arg_ptr, int);    va_end(arg_ptr);    printf("%d %d\n", i, j);    return;}int32_t main(int32_t argc,char *argv[]){    simple_va_fun(100);    simple_va_fun(100,500);    simple_va_fun(100,500,1000);}#endif // 1
原创粉丝点击