通过函数通过c数组进行迭代
Iterating through c array through function
因此,我试图找到一种方法,在不知道大小的情况下,通过传递到函数中的数组进行迭代。由于数组不是以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;
相关文章:
- 实现一个在集合上迭代的模板函数
- 如何在C++中将迭代器作为函数参数传递
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 调用迭代函数的次数
- HPX 是否提供具有粒度控制的基于任务的并行化迭代函数?
- 如何将递归函数(具有两个基本情况)转换为迭代函数
- 将递归函数转换为迭代函数
- 当我计算它并给我 O(n^3) 时,这个迭代函数是如何是 O(n/2) 的
- C 的自定义迭代函数
- 如何记录C 重复迭代函数的总时间
- 使用迭代函数调用初始化std::vector
- 将递归可变参数模板函数转换为迭代函数
- 将迭代函数转换为递归函数
- 将迭代函数转换为递归函数
- c++使用迭代函数进行编译
- 模板类中向量向量的迭代函数构建
- 将迭代函数转换为递归函数
- 这个递归函数是如何自动转换成迭代函数的
- 在编译时迭代函数参数类型