通过函数迭代c数组

时间:2014-09-28 18:30:47

标签: c++ arrays function loops pointers

所以我试图找出一种方法来迭代,但是在不知道大小的情况下传递给函数的数组。我用我的代码遇到无限循环,因为数组不是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;

1 个答案:

答案 0 :(得分:1)

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

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;
}

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

#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;
相关问题