//main.cpp :: main() map<char, vector<bool> > temp= make_test_val(); cout<< toString(temp);
用模板实现toString(任意类型) 而后就方便了ide
如下是代码:ui
//tools.h #include<map> #include<vector> using namespace std; //---toString--- //builder class tostring_bulider{ public: string _str; string _prefix; string _comma; string _suffix; bool first_item; tostring_bulider(){ first_item= true; _prefix= "["; _suffix= "]"; _comma= ", "; } void prefix(){ _str+= _prefix; } template<typename T> void push(const T& item){ if(first_item){ first_item= false; }else{ _str+= _comma; } _str+= ::toString(item); } void suffix(){ _str+= _suffix; } string toString()const{return _str;} }; class tostring_map_bulider{ public: string _str; string _prefix; string _comma; string _eq; string _suffix; bool first_item; tostring_map_bulider(){ first_item= true; _prefix= "{"; _suffix= "}"; _comma= ", "; _eq= ":"; } void prefix(){ _str+= _prefix; } template<typename T> void push(const T& item){ if(first_item){ first_item= false; }else{ _str+= _comma; } _str+= ::toString(item.first)+ _eq+ ::toString(item.second); } void suffix(){ _str+= _suffix; } string toString()const{return _str;} }; //etc. //default type string toString(const string& s){return s;} //system type template<typename T> string toString(const T& v){ return v.toString(); } template<> string toString<char>(const char& v){ return string()+v; } template<> string toString<bool>(const bool& v){ return v? "true": "false"; } //etc. //Container template<typename T, typename Tfmt> string toString(const T& v, Tfmt fmter){ fmter.prefix(); for(auto iter = begin(v); iter!=end(v); ++iter) fmter.push(*iter); fmter.suffix(); return move(toString(fmter)); } //std Container template<typename T> string toString(const vector<T>& v){ return toString(v,tostring_bulider()); } template<typename Tk, typename Tv> string toString(const map<Tk,Tv>& v){ return toString(v, tostring_map_bulider()); } //etc.
可是这样显示出来是这样的:spa
{a:[false, false, true, false], b:[false, false, true, false, true, false, true, false]}能够添加如下代码:
//main.cpp class my_tostring_map_bulider: public tostring_map_bulider{ public: string toString_vector_bool(const vector<bool>& v){ string ret; for(auto iter= begin(v); iter!=end(v); ++iter) ret+= *iter? "1": "0"; return ret; } void push(const pair<char, vector<bool> >& item){ if(first_item){ first_item= false; }else{ _str+= _comma; } _str+= ::toString(item.first)+ _eq+ toString_vector_bool(item.second); } };
//main.cpp :: main() map<char, vector<bool> > temp= make_test_val(); cout<< toString(temp, my_tostring_map_bulider());
输出是这样的:code
{a:0010, b:00101010}