c++ - 是否可以使用标准库的查找、开始和结束来编写 in_array 辅助函数?

标签 c++

an answer在 SO 上,它解释了如何执行对数组中值的搜索。来自 PHP 背景,我习惯了一定程度的动态类型化——C++ 中不存在的东西,这会带来一些挑战。那么是否可以创建一个辅助函数来执行类似于 PHP 的 in_array($needle, $haystack) (例如,使用链接答案中的代码)用作速记?

写完这段代码后,我明白了(明显地)为什么它不起作用——参数并没有真正表示类型。如果有的话,可以做些什么来规避这种情况,这样做是不是一种不好的做法?

bool in_array(needle, haystack) {
    // Check that type of needle matches type of array elements, then on check pass:
    pointer* = std::find(std::begin(haystack), std::end(haystack), needle);
    return pointer != std::end(haystack);
}

编辑:要特别清楚,我真的不想对 C++ 进行 PHPize - 我一直在寻找一种通常在 C++ 中完成的方式!

最佳答案

这就是模板的用途:

template <class ValueType, class Container>
bool in_array(const ValueType& needle, const Container& haystack) {
// Check that type of needle matches type of array elements, then on check pass:
    return std::find(std::begin(haystack), std::end(haystack), needle) != std::end(haystack);
}

前提是 Container 类型是 C 风格的数组,或者它具有可访问的成员方法 begin()end();并且 ValueType 可转换为 Container::value_type,这应该可行。


话虽如此,模板并不是一个容易处理的话题。如果你想了解更多,我推荐你其中之一 good C++ books

关于c++ - 是否可以使用标准库的查找、开始和结束来编写 in_array 辅助函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56647180/

相关文章:

c++ - 如何找到程序当前状态下的最大可分配内存量

c++ - UI 未在 QT 设计器中更新

c++ - 带有 BIF_BROWSEFORCOMPUTER 和 SHGetPathFromIDList 的 SHBrowseForFolder 不工作

c++ - 在库中使用未定义的外部变量会在 macOS 中产生链接器错误

c++ - 如果没有c++编译器,C语言可以调用c++编写的DLL吗?

C++ SDL "Native' 已退出,代码为 -1073741701 (0xc000007b)”

c++ - OpenGL 获取设备上下文

c++ - 防止 "Program too big to fit in memory"的链接器选项

带有小键盘键的 C++ Qt QShortcut

c++ - 如何使用成对的 STL 二进制搜索操作?