C++ map 转 string(自己实现的小代码)

实际应用中需要将map的内容打印出来作为日志,因此写了一个通用函数。用到了函数模板和函数重载。

注:使用g++进行编译。

/*************************************************************************
    > File Name: maptoStr.cpp
    > Author: chenhui
    > Mail: *********
    > Created Time: 2016年05月27日 16:32:09
 ************************************************************************/
#include
#include


#include
#include


using namespace std;



string getString(const int32_t& a)
{
        char c[1024]={0};
        snprintf(c,sizeof(c),"%d",a);
        return c;
}


string getString(const int64_t& a)
{
        char c[1024]={0};
        snprintf(c,sizeof(c),"%lld",a);
        return c;
}


string getString(const string& s)
{
        return s;
}


template
string mapToString(std::map& m)
{
        string str="";
        typename std::map::iterator it = m.begin();
        for(;it != m.end();it++)
        {
                str += "<";
                str += getString(it->first) + "," + getString(it->second);
                str += ">";
        }
        return str;
}




int main()
{
        std::map mm;
        mm[10]="ddddd";
        mm[23]="sssss";
        string str = mapToString(mm);
        cout<         return 0;
}

你可能感兴趣的:(c/c++)