通过函数通过c数组进行迭代

Iterating through c array through function

本文关键字:迭代 函数 数组      更新时间:2023-10-16

因此,我试图找到一种方法,在不知道大小的情况下,通过传递到函数中的数组进行迭代。由于数组不是以NULL结尾的,所以我的代码会遇到无限循环。由于数组是通过函数变成指针的,所以我不能使用sizeof(array)/sizeof(int)来获取元素的数量。有没有任何方法可以在不使用NULL终止数组的情况下完成此操作?

我的查找功能:

int find(const int* arr, int val)
{
    int pos = 0;
    while (arr != NULL)
    {
        if (*arr == val)
        {
            return pos;
        }
        pos++;
    }
    return -1;
};

我的主页:

int IntArr[] = { 1, 2, 3, 4, 5 };
int index = find(IntArr, 4);
cout << "find(IntArr, 4)" << endl;
cout << "index: " << index << endl << endl;

例如,您可以定义一个模板函数,通过引用接受数组

template <size_t N>
int find( const int ( & arr )[N], int value )
{
    int pos = 0;
    while ( pos < N && arr[pos] != value ) ++pos;
    return pos == N ? -1 : pos;
}

考虑到在报头<algorithm>中声明了标准算法std::find。你可以写例如

#include <algorithm>
#include <iterator>
//..
int IntArr[] = { 1, 2, 3, 4, 5 };
auto ptr = std::find( std::begin( IntArr ), std::end( IntArr ), 4 );
cout << "find( std::begin( IntArr ), std::end( IntArr ), 4)" << endl;
cout << "index: " << std::distance( std::begin( IntArr ), ptr ) << endl << endl;