如何编写模板来检查给定值是否在数组中
How can I write a template to check if a given value is in an array
根据上一个问题的答案,我在下面编写了模板,如果数组包含传递的值,则应返回true,否则应返回false。
template <typename Type>
bool Contains(const Type container[], const Type& value) {
return std::any_of(
std::begin(container), std::end(container),
[&value](const Type& contained_value) { return value == contained_value; });
}
当我尝试编译时,出现以下错误:
error: no matching function for call to 'begin'
std::begin(container), std::end(container),
是什么导致std::begin
失败?std::begin 文档显示它适用于数组。在这个特定实例中,我在枚举(而不是枚举类(上实例化模板。
Contains
的类型是错误的,因此container
被推导出为const int *&
,它们没有覆盖std:begin
来自 g++ 的错误消息更清晰:
main.cpp:在实例化 'bool Contains(const Type*, const Type&( [使用 Type = int]':main.cpp:18:34:从这里需要
main.cpp:9:17:错误:调用"开始"(const(没有匹配函数 int*&('
这是固定代码。你需要将数组作为数组类型(int[3]
(传递,以便std::end
从类型中计算出数组的长度。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
template <typename Type, std::size_t N>
bool Contains(Type (&container)[N], const Type& value) {
return std::any_of(
std::begin(container), std::end(container),
[&value](const Type& contained_value) { return value == contained_value; });
}
int main()
{
int a[] = {1,2,3};
int val = 1;
int val2 = 4;
bool result = Contains(a, val);
bool result2 = Contains(a, val2);
std::cout << result << std::endl;
std::cout << result2 << std::endl;
}
相关文章:
- 如何找到大小'x'数组是否完全填充,在C++?
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 是否基于数组B整数打印数组A中的整数
- 检查TCHAR数组输入是否为带符号整数C++
- 堆栈和队列是否像C++中的数组一样传递?
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 是否假定reinterpret_cast<char*>(myTypePtr)指向数组?
- 如果分配数组引发异常,是否应该释放该数组
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 我是否不正确地集中了这些字符数组?
- 是否可以就地构造一个固定大小的数组作为函数参数?
- 在 c++ 中是否允许创建具有运行时边界的数组?
- C++ 返回指向函数内定义的静态数组的指针是否有效?
- 检查输入 std::array 指针数据是否等于某个常量数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- C++:在多个线程中访问同一数组/向量的不同单元格是否会产生数据竞赛?
- 将对象的字节复制到数组并再次复制回来是否安全
- 是否可以将结构数组别名为结构成员数组?
- 当另一个数组是内存集时,内存集是否会更改数组长度?
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?