web-dev-qa-db-ja.com

指定された値の場合、配列のインデックスを検索します

値が格納されている配列のインデックスを取得したい。配列のその時点でのアイテムの値を知っています。 C#のfindIndex関数に似ていると思います。たとえば、array [2] = {4、7、8}です。値が7であることはわかっていますが、配列[1]にあることがわかっている場合、インデックスの値1を取得するにはどうすればよいですか?

7
user1798299

たとえば、次のように対応する関数を定義できます

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

また、type_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;
    }
} 

出力は

The index of the element with value 7 is 1

それ以外の場合は、私が上に示したように、自分で関数を記述する必要があります。

配列がソートされている場合、ヘッダーで宣言された標準C関数bsearchを使用できます<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;
}
8

まず、引数リストに配列のサイズ情報が含まれることが重要です。つまり、ポインターを配列に渡しますonlyは、配列の要素数を知るのに十分な情報を提供しません。引数は関数へのサイズ情報のないポインタ型に減衰します。

したがって、次のようなことができます。

int findIndex(int *array, size_t size, int target) 
{
    int i=0;
    while((i<size) && (array[i] != target)) i++;

    return (i<size) ? (i) : (-1);
}

小さなアレイの場合、このアプローチは適切です。非常に大きな配列の場合、並べ替えと二分検索によってパフォーマンスが向上します

1
ryyker