gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:56:59 25 4
gpt4 key购买 nike

所以我阅读了有关此的其他 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com