c++ - 是否可以使用 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++ 中完成的方式!
解决方案
这就是模板的用途:
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++ 书籍
推荐阅读
- c++ - 无法获取 WPF 的 TextBox 控件的背景颜色
- git - 在 gitahead 中创建带注释的标签
- javascript - 基于长度如何在 vuejs 中验证确认密码?
- r - 如何输出两个网格图(grid.draw)并在shinyapp中下载?
- postgresql - PL/pgSQL 函数以递归方式获取参数和搜索表
- python - 此代码给出索引错误。我的讲师的代码在 test_board 中传递了另一个字符串,该字符串也未显示在输出中
- web - HTTP 请求在失眠和请求(python)中有效,但在 axios 中无效
- asp.net-core - 在 ASP Net Core 中的表中添加可点击的行
- dart - 无效值:不在包含范围内 4..5:6 子列表颤动
- javascript - 如何在 JavaScript 中格式化输出