r/cpp • • Oct 15 '13

C++ has become a scripting language

http://voices.canonical.com/jussi.pakkanen/2013/10/15/c-has-become-a-scripting-language/
1 Upvotes

53 comments sorted by

View all comments

Show parent comments

2

u/notlostyet Oct 15 '13 edited Oct 15 '13

I agree with (2) and (3) especially. I tried to shorten it but only came up with this:

#include <fstream>
#include <iterator>
#include <string>
#include <set>
#include <algorithm>

using namespace std;

int main (int, char **argv) {
    ifstream ifile(argv[1]);
    ofstream ofile(argv[2]);
    ostream_iterator<string> osi (ofile, "\n");
    multiset<string> data;
    string line;
    while (getline (ifile, line)) {
        data.insert(std::move(line));
    }
    copy (begin(data), end(data), osi);
    return 0;
}

which is just 1 line shorter.

3

u/0xa0000 Oct 15 '13

You can condense that a bit even without using non-idiomatic constructs, saving three lines:

int main (int, char **argv) {
    ifstream ifile(argv[1]);
    ofstream ofile(argv[2]);
    multiset<string> data;
    for (string line; getline (ifile, line); ) {
        data.insert(std::move(line));
    }
    copy (begin(data), end(data), ostream_iterator<string>(ofile, "\n"));
}

1

u/notlostyet Oct 15 '13 edited Oct 15 '13

Nice catch. Initially 'line' was kept outside of the loop for efficiency, but since we're moving in to the set anyway there's no point

1

u/F-J-W Oct 15 '13

Even better: they way he uses it inside the for-loop is equivalent to your version. I've never seen it that way before, but I guess, I'll do it that way from now on.