A few weeks back, I posited the question, "What is the best way to format a comma delimited list?"
After seeing all of the succinct ways to accomplish this in other languages, I got a little jealous and decided to write this C++ algorithm which acts about the same.
I feel like there must be a c++ standard library way of doing this that I'm some how overlooking.
template <typename InItr> std::string join(InItr begin, InItr end, const std::string &joiner) { std::string ret; while (begin != end) { std::stringstream ss; ss << *begin; ret += ss.str(); ++begin; if (begin != end) { ret += joiner; } } return ret; }
Usage:
//With an array: int vals[] = {1,17,9}; std::cout << join(&vals[0], &vals[sizeof(vals)/sizeof(int)], ", ") << std::endl; //With a vector: std::vector<int> vec; vec.push_back(1); vec.push_back(17); vec.push_back(9); std::cout << join(vec.begin(), vec.end(), ",") << std::endl;
Recent comments
10 sec ago
2 hours 55 min ago
2 hours 55 min ago
13 hours 9 min ago
14 hours 37 min ago
14 hours 37 min ago
14 hours 37 min ago
21 hours 54 min ago
2 weeks 3 days ago
4 weeks 4 days ago