如何编写模板来检查给定值是否在数组中

How can I write a template to check if a given value is in an array

本文关键字:是否 数组 何编写 检查      更新时间:2023-10-16

根据上一个问题的答案,我在下面编写了模板,如果数组包含传递的值,则应返回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;
}