3 ms·
Without looking at any other solutions, I whipped up a one-off 37-line C++11 program that is easily twice as fast as the best D or Rust one, with no special tri
by ncmncm 9y ago
Without looking at any other solutions, I whipped up a one-off 37-line C++11 program that is easily twice as fast as the best D or Rust one, with no special tricks. (Change out the uses of "auto" and it qualifies as C++98.)
I am appalled that a 125-line program to do such a simple job could win. If that was the best they could do, I would have kept the challenge open until something better came in.
I haven't tried the other programs on one-field files, or where the field selected is the first, or the last. Did you?
#include <iostream>
#include <fstream>
#include <streambuf>
#include <algorithm>
#include <string>
int main(int, char** argv) {
std::ifstream in(argv[1]);
std::string head;
if (!(in >> head)) return std::cout << "input file missing\n", 1;
head = "," + head + ",";
auto sub = std::string(argv[3]);
auto target = "," + std::string(argv[2]) + ",";
auto pos = head.find(target);
if (pos == std::string::npos)
return std::cout << "column name doesn’t exists in the input file\n", 1;
auto skip_pre = pos ? std::count(&head[0], &head[pos], ',') : 0;
auto skip_post = std::count(
&head[pos + target.size()], &head[head.size()], ',');
std::ofstream out(argv[4]);
auto ib = in.rdbuf(), ob = out.rdbuf();
ob->sputn(&head[1], head.size()-2); ob->sputc('\n');
bool skipping = pos == 0;
for (int c = 0, count = skip_pre; (c = ib->snextc()) != EOF; ) {
if (c == ',' || c == '\n') {
if (skipping) {
count = skip_post + skip_pre;
skipping = count == 0;
ob->sputn(&sub[0], sub.size());
} else if (--count == 0) {
skipping = true;
}
ob->sputc(c);
} else if (!skipping)
ob->sputc(c);
}
}
- geezerjay 9y ago> I am appalled that a 125-line program to do such a simple job could win. The goal of that challenge was to pack the most C++17 features in a program, and it was just a challenge organized by a couple of blogs. The winner was also a self-confessed amateur. That's a telltale sign of how many people have participated, and the level of engagement that the challenge had.