有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/