首页 > 解决方案 > 是否可以使用 std 库的 find、begin 和 end 编写 in_array 辅助函数?

问题描述

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);
}

编辑:为了更加清楚,我真的不想 PHPize C++ - 我正在寻找的是一种通常在 C++ 中完成的方式!

标签: 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,这应该可以。


话虽如此,模板并不是一个容易处理的话题。如果您想了解更多信息,我向您推荐一本好的 C++ 书籍


推荐阅读