C++ implode function


Here is a quick implode function for C++.
#include <iostream>
#include <string>
 
using namespace std;
 
string implode( const string &glue, const vector<string> &pieces );
 
int main(int argc, char *argv[])
{
    vector<string> v;
    v.push_back("1");
    v.push_back("2");
    v.push_back("3");
    cout << implode(" ", v)<< endl; // "1 2 3"
}
 
string implode( const string &glue, const vector<string> &pieces )
{
    string a;
    int leng=pieces.size();
    for(int i=0; i<leng; i++)
    {
        a+= pieces[i];
        if (  i < (leng-1) )
            a+= glue;
    }
    return a;
}

code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)

Aleksandr on 2010-11-18 11:10:10
That smell good as hell! Exatly what I was lookin for. :))