是否可以使用std库的find,begin和end编写in_array helper函数?

时间:2019-06-18 10:34:47

标签: c++

SO上有an answer,它说明了如何在数组中搜索值。来自PHP的背景,我习惯了一定程度的动态类型化-C ++中不存在这种类型,这随后带来了一些挑战。这样,是否有可能创建一个类似于PHP x3.py的辅助函数(例如,使用链接的答案中的代码)作为速记?

已经编写了此代码段,我(切实地)理解了为什么它不起作用-参数实际上并没有表示类型。可以采取什么措施来规避这种情况,这样做是不好的做法吗?

connect_vpn

编辑:需要特别说明的是,我真的不想PHPize C ++-我一直在寻找的是通常在C ++中完成的方式!

2 个答案:

答案 0 :(得分:4)

这就是模板的用途:

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

之一

答案 1 :(得分:1)

模板让您编写函数

template <class T, class U, size_t N>
bool in_array(const T& needle, U (&haystack)[N]) {
    // 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);
}

但是我不太确定这能为您带来什么,它仍然是静态输入的。静态类型当然是一件好事。

未经测试的代码。