c++ - 在 find() 中提供 bool 值是不是不好的风格?

标签 c++ iterator find

在“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/

相关文章:

c++ - 如何将现有的Q_PROPERTY重新定义为REQUIRED?

C++ 传递带有范围参数的回调

c++ - 在创建自己的数据结构时,我应该使用迭代器还是索引来提供从外部的访问?

linux - 为什么 'find' 命令失败没有错误?

c++ - 为 C 和 C++ 安装 MessagePack 实现时出现链接器错误

c++ - 为什么没有 std::string_view 的模板构造函数?

python - 在numpy中生成一个n维坐标数组

c++ - 我们可以在没有 'advance' 函数的情况下增加迭代器多个位置吗?

bash - 如何使用bash获取带有fo o.bar名称的文件夹的大小?

bash - 从 Unix 命令行查找给定子目录中的文件