我想检索存储值的数组中的索引。我知道数组中该项的值。我认为它类似于c#中的findIndex函数。 例如,array [2] = {4,7,8}。我知道值是7,如果我知道它在数组[1],我怎么得到索引的值1?
答案 0 :(得分:8)
例如,您可以通过以下方式定义相应的功能
size_t FindIndex( const int a[], size_t size, int value )
{
size_t index = 0;
while ( index < size && a[index] != value ) ++index;
return ( index == size ? -1 : index );
}
也可以使用int。
类型而不是类型size_t但更好的方法是使用在标头std::find
中声明的标准算法std::find_if
或<algorithm>
,前提是您使用C++
例如
#include <algorithm>
#include <iterator>
int main()
{
int a[] = { 4, 7, 8 };
auto it = std::find( std::begin( a ), std::end( a ), 7 );
if ( it != std::end( a ) )
{
std::cout << "The index of the element with value 7 is "
<< std::distance( std::begin( a ), it )
<< std::endl;
}
}
输出
The index of the element with value 7 is 1
否则你必须自己编写这个函数,因为我展示了abve。:)
如果数组已排序,您可以使用标题bsearch
中声明的标准C函数<stdlib.h>
例如
#include <stdio.h>
#include <stdlib.h>
int cmp( const void *lhs, const void *rhs )
{
if ( *( const int * )lhs < *( const int * )rhs ) return -1;
else if ( *( const int * )rhs < *( const int * )lhs ) return 1;
else return 0;
}
int main()
{
int a[] = { 4, 7, 8 };
int x = 7;
int *p = ( int * )bsearch( &x, a, 3, sizeof( int ), cmp );
if ( p != NULL ) printf( "%d\n", p - a );
return 0;
}
答案 1 :(得分:0)
首先,重要的是参数列表包含数组的大小信息,即将指针传递给数组 并不足够信息,以了解该数组有多少元素。参数衰减为指针类型,函数没有大小信息。
因此,你可以这样做:
int findIndex(int *array, size_t size, int target)
{
int i=0;
while((i<size) && (array[i] != target)) i++;
return (i<size) ? (i) : (-1);
}
对于小阵列,这种方法很好。对于非常大的数组,一些排序和二进制搜索可以提高性能
答案 2 :(得分:0)
这是我的版本,没有其他变量。
// Return index of element starting
// Return -1 if element is not present
int indexOf(const int elm, const int *ar, int ar_cnt)
{
// decreasing array count till it reaches negative
// arr_cnt - 1 to 0
while (ar_cnt--)
{
// Return array index if current element equals provided element
if (ar[ar_cnt] == elm)
return ar_cnt;
}
// Element not present
return -1; // Should never reaches this point
}
希望评论是不言自明的!