Skip to content

Instantly share code, notes, and snippets.

@diaasami
Last active August 29, 2015 14:18
Show Gist options
  • Save diaasami/f54a97201d3c46566c47 to your computer and use it in GitHub Desktop.
Save diaasami/f54a97201d3c46566c47 to your computer and use it in GitHub Desktop.
A function similar to Python's join for C++'s vector, probably should be generalized for all containers but I'll leave that for another day.
template <typename T>
string join(const vector<T> &v, const string &sep)
{
ostringstream oss;
for (const T &element: v)
oss << element << sep;
const string out = oss.str();
return v.empty() ?
out :
out.substr(0, out.length() - sep.length());
}
// example usage
// cout << join(output, ", ") << endl;
// cout << join(vector<float>(5, 1.1f), ", ") << endl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment