译自five popular myths about c++ --by Bjarne Stroustrup (5)



Myth 5: "C++ is for large, complicated, programs only"
c++ 只是用于大型复杂的程序


C++ is a big language. The size of its definition is very similar to those of C# and Java. But that does not imply that you have to know every detail to use it or use every feature directly in every program. Consider an example using only foundational components from the standard library:
c++ 是一门大语言。它的定义大小和java c# 差不多。但那并不意味着你必须知道每一个使用细节或是在每一个程序中直接使用每一个特征。思考一个仅使用标准库基础组件的例子:

set get_addresses(istream& is)
{
  set addr;
  regex pat { R"((\w+([.-]\w+)*)@(\w+([.-]\w+)*))"}; // email address pattern
  smatch m;
  for (string s; getline(is,s); )                    // read a line
    if (regex_search(s, m, pat))                     // look for the pattern
      addr.insert(m[0]);                             // save address in set
  return addr;
}


I assume you know regular expressions. If not, now may be a good time to read up on them. Note that I rely on move semantics to simply and efficiently return a potentially large set of strings. All standard-library containers provide move constructors, so there is no need to mess around with new.
假设你了解正则表达式。如果不会,现在或许是时候读一下了。注意,我依靠 move 语法对可能返回的大串字符进行简化优化。所有标准库容器都提供了移动构造函数,所以没必要用 new.


For this to work, I need to include the appropriate standard library components:
为了正常运行,我需要包含适当的标准库组件:

#include
#include
#include
#include
#include
using namespace std;

Let’s test it:
测试下:

istringstream test {  // a stream initialized to a sting containing some addresses
  "asasasa\n"
  "[email protected]\n"
  "[email protected]$aaa\n"
  "[email protected] aaa\n"
  "asdf bs.ms@x\n"
  "$$bs.ms@x$$goo\n"
  "cft [email protected]@yy asas"
  "qwert\n"
};

int main()
{
  auto addr = get_addresses(test);  // get the email addresses
  for (auto& s : addr)              // write out the addresses
    cout << s << '\n';
}

This is just an example. It is easy to modify get_addresses() to take the regex pattern as an argument, so that it could find URLs or whatever. It is easy to modify get_addresses() to recognize more than one occurrence of a pattern in a line. After all, C++ is designed for flexibility and generality, but not every program has to be a complete library or application framework. However, the point here is that the task of extracting email addresses from a stream is simply expressed and easily tested.
这只是一个例子。只要简单的修改下 get_addresses, 将正则表达式作为参数,就可以查找 URLs 或其他,简单修改下就可以识别一行里更多的匹配。毕竟 c++ 是为便捷和通用而生,但并不是每一个程序都可以成为一个完整的库或应用框架。重点是对于从流中提取 email 地址这个任务可以简单实现和测试。

你可能感兴趣的:(c++)