no = 0;
? ? ifstream fp(file);
? ? {
? ? ? ? // Does fp.fail() preserve errno?
? ? ? ? int save_errno = errno;
? ? ? ? if (fp.fail()) {
? ? ? ? ? ? throw("Cannot open '" + string(file) + "': " + strerror(save_errno));
? ? ? ? }
? ? }
?
? ? unordered_map word_count {};
? ? string word;
?
? ? while (fp >> word) {
? ? ? ? word_count[word] += 1;
? ? }
?
? ? fp.close();
?
? ? return accumulate(
? ? ? ? word_count.cbegin(),
? ? ? ? word_count.cend(),
? ? ? ? 0,
? ? ? ? [](int sum, auto& el) { return sum += el.second; }
? ? );
}
20 行代码用于 #include 和 using 声明可能看起来有点多,但是我抬眼 using namespace std,也讨厌不断地输入 std::... 更多的是因为我喜欢较短的代码行。
首先要注意的是没有看得见的显式的内存分配。容器集装箱管理自己的内存。
第二,这是一个大问题:我们有自动导入(autovivification)!
?
unordered_map word_count {};
string word;
?
while (fp >> word) {
? ? word_count[word] += 1;
}
?
第三,我们有 lambda 表达式:
return accumulate(
? ? word_count.cbegin(),
? ? word_count.cend(),
? ? 0,
? ? [](int sum, auto& el) { return sum += el.second; }
);
?
在这背???,accumulate 将内部变量初始化为 0,并调用一个匿名函数,其最后一个参数指定为当前值,以及word_count的下一个元素。
现在,我不得不承认,我不知道这些特性是如何实现的,但是 Microsoft Visual C++ 2015 RC 成功运行了,微软似乎终于赶上了在该领域的最新发展。
然而,一切都不乐观。尽管 boost libraries 填补了许多空白,而且标准库提供了令人印象深刻的构件,但是也很难战胜 Perl 和 CPAN 结合带来的那种编写可在任何地方完美运行的可移植代码的便利性。
例如,我能找到一个平台无关的库,可以让我在不需要 Excel 的情况下解析或创建 Excel 文件吗?这个库能够用 clang、g++ 和 cl 轻易地编译出来吗?好像不太可能。
我真的非常感谢标准委员会的人们的辛勤工作,和那些开发编译器,众多库的人们。它们让我不必在编写 C++ 程序时辛苦的思考。
这让我在真正控制我的计算机时还能感觉舒适。
在这里,我真的非常感谢。
你可以评论本文。
英文原文:Can C++ become your new scripting language?