Thursday, January 19, 2012

Why not C++ all the time?

In the why-we-don't-prefer-programming-in-c++ exhibit of evidence:

python: 
  result = line.split(',')

C#:
  var result = line.Split(',');

C++:
  vector<string> result;
  ostringstream sourcestream(sourceString);
  copy(
     istream_iterator<string>(sourcestream), 
     istream_itearator<string>(), 
     back_inserter<vector<string> >(result) 
  );


Special thanks to StackOverflow  Zunino at Stack Overflow for this answer, one of the most concise and standards-respecting.

8 comments:

  1. A little bit of misdirection there - no declarations for the variable holding the result in the other languages, so these aren't purely equivalent.

    ReplyDelete
  2. Anonymous - you are right. I have just added those in for comparison. I don't want to be unfair, since I owe much of my early career to C++ programming.

    ReplyDelete
  3. While the C++ version is more verbose than the other two example language, it is also unclear how the split operation is occurring (i.e., is it being split on space, or comma as the other two examples are).

    ReplyDelete
  4. Boost has split. Yet another unfair comparison

    ReplyDelete
    Replies
    1. Yup, Boost makes things better, but only if you're willing to go get a fresh cup of coffee every time you compile.

      Using Boost can really change your perspective on how far that Starbucks is to walk to...

      Delete
  5. Hi Tim--

    I find C++ a less-than-satisfying language that I'm once again returning to. The second answer on StackOverflow (which also had a few more upvotes) uses boost--not really a standards-disrespecting library. The boost solution distills to a far more expressive and concise solution:

    vector tokens;
    split(tokens, "string to split", is_any_of("\t "));

    ReplyDelete
  6. D is defining split(line, ',') in std.array.

    And it is native code just like C++, because sometime, it matter ;)

    PS: The URL filter doesn't like my website, so I post in anonymous :/

    ReplyDelete