在“Accelerated C++: Practical Programming by Example”中,第 6.1.3 章是“算法”库中的 find()
示例:
我们要检查 char
是否在字符串中:
bool find_char(char c){
string str = "asdf";
return find(str.begin(), str.end(), c) != str.end();
}
然后就是find()
的解释:
It is similar to find_if, except that instead of calling a predicate, it looks for the specific value given as its third argument. As with find_if, if the value that we want is present, the function returns an iterator denoting the first occurrence of the value in the given sequence. If the value is not found, then find returns its second argument.
这让我想知道为什么我们不使用更短更简洁的版本:
bool find_char(char c){
string str = "asdf";
return find(str.begin(), false, c); //does not compile, see Top Answer
}
这被认为是糟糕的风格吗?该代码有问题吗?
最佳答案
问题是第二个参数不仅是在 haystack 中找不到针时返回的值,第二个参数也是 haystack 本身的(指针或迭代器)末尾。您将 false
作为 std::find
的第二个参数的示例将无法编译,因为 false
不是一种迭代器,当然也不是以任何方式与 std::string::begin()
相媲美或兼容,更不用说形成范围的结尾了。
关于c++ - 在 find() 中提供 bool 值是不是不好的风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162076/