join使用

来源:互联网 发布:微信头像 知乎 编辑:程序博客网 时间:2024/06/06 04:46
// 在日常开发中,经常会碰到需要将多个字符串以某些相同的分隔字符串连接起来的情形//      "select * from t where name in ('a', 'b', .. , 'z')"中的"', '"//      "insert into t(name) values ('a'), ('b')"中的 "'), ('" //      <table> <tr><td>a</td><td>b</td></tr> <tr><td>a</td></tr> </table>中的 "</td><td>"// ....//// 于是,我写一个模板join用来支持这一类开发需求//#include <iostream>#include <string>#include <vector>#include <sstream>using namespace std;template <class type_a, class type_b>string& // 返回值string&方便下面的使用场景 ostream << join(...); string b = join(...);join( const type_a &begin, const type_a &end,   // 方便iterator的使用        const type_b &t,                        // 相同的分隔字符串        string& result                          // 存放结果, 注意:不要用函数内的局部变量,函数返回引用时会出现错误        ) {    result.clear();                             // 为了后面测试方便加的,可根据需要选择去留    for (type_a it=begin; it!=end; ++it)    {        if (!result.empty())            result.append(t);        result.append(*it);    }    return result;}int main(int argc, char** argv){    vector<string> strs;    strs.push_back("a");    strs.push_back("b");    strs.push_back("c");    string result;    join(strs.begin(), strs.end(), ",", result);    cout << result << endl;    join(strs.begin(), strs.end(), "\t", result);    cout << result << endl;    const string& sa = join(strs.begin(), strs.end(), "\n", result);    cout << sa << endl;    stringstream ss;    ss << "select * from t_a where name in('"        << join(strs.begin(), strs.end(), "','", result)        << "')"        << endl;    cout << ss.str() << endl;    return 0;}

原创粉丝点击