Reply to comment

Formatting a Comma Delimated List Redux

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;

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
4 + 16 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.