C++ 在数组中查找一个整数

标签 c++

所以我阅读了有关此的其他 Stack 帖子,他们都建议我使用 find。我正在尝试这样做,但它对我不起作用。

bool findInArray(int number, int array[]){
    // Finds if the number is in the array
    bool exists = find(begin(array), end(array), number) != end(array);
    return exists;

但我不断收到以下错误:

error: no matching function for call to ‘begin(int*&)’

这里甚至是公认的答案:How can I check if given int exists in array?

最佳答案

你需要一个模板:

template <std::size_t N>
bool findInArray(int number, const int (&array)[N]) {
  // Finds if the number is in the array
  return std::find(std::begin(array), std::end(array), number) != std::end(array);
}

您还需要按左值传递数组,因为在 C++ 中不能按纯右值传递数组,相反,数组会退化为指向其第一个元素的指针,从而丢失大小信息。

关于C++ 在数组中查找一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213758/

相关文章:

c++ - Eclipse 中 C++ 重构支持的状态如何?

c++ - OpenMP:如何刷新指针目标?

c++ - opencv中基于ROI的KLT光学跟踪器

c++ - c++中的继承,里面输出

c++ - 位 c 操作

c++ - 将非 char* 参数传递给 execvp

c++ - 满足条件后如何终止函数

c++ - 互斥体应该是可变的吗?

c++ - 如何在 C++ 中初始化结构

c++ - Visual 2010 不断告诉我 "error: Expression must have class type"