我想检索存储值的数组中的索引.我知道数组中该项的值.我认为它类似于c#中的findIndex函数.例如,array [2] = {4,7,8}.我知道值是7,如果我知道它在数组[1],我怎么得到索引的值1?
例如,您可以通过以下方式定义相应的功能
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 );
}
Run Code Online (Sandbox Code Playgroud)
而不是类型size_t,您可以使用int类型.
但更好的方法是使用标准算法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;
}
}
Run Code Online (Sandbox Code Playgroud)
输出是
The index of the element with value 7 is 1
Run Code Online (Sandbox Code Playgroud)
否则你必须在我展示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;
}
Run Code Online (Sandbox Code Playgroud)