名前空間
変種
操作

bsearch

提供: cppreference.com
< c‎ | algorithm
2015年11月30日 (月) 05:43時点におけるP12bot (トーク | 投稿記録)による版

ヘッダ <stdlib.h> で定義
void* bsearch( const void* key, const void* ptr, size_t count, size_t size,
               int (*comp)(const void*, const void*) );
keyが指す配列内ptrが指す要素に等しい要素を検索します。配列はsizecountsize要素が含まれています。関数はcompがオブジェクトの比較に使用される、によって指さ.
Original:
Finds an element equal to element pointed to by key in an array pointed to by ptr. The array contains count elements of size size. Function pointed to by comp is used for object comparison.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

目次

パラメータ

key -
を検索するための要素へのポインタ
Original:
pointer to the element to search for
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
ptr -
検討する配列へのポインタ
Original:
pointer to the array to examine
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
count -
配列内の要素の数
Original:
number of element in the array
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
size -
バイト単位で配列内の各要素の大きさ
Original:
size of each element in the array in bytes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
comp - 第1引数が第2引数より小さい場合は負の整数値、第1引数が第2引数より大きい場合は正の整数値、第1引数と第2引数が同等な場合はゼロを返す比較関数。 key is passed as the first argument, an element from the array as the second.

比較関数のシグネチャは以下と同等であるべきです。

 int cmp(const void *a, const void *b);

関数は渡されたオブジェクトを変更してはならず、同じオブジェクトに対してはその配列内の位置にかかわらず一貫した結果を返さなければなりません。

値を返します

見つかった要素または別の方法でNULLへのポインタ..
Original:
pointer to the found element or NULL otherwise.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

#include <stdlib.h>
#include <stdio.h>
 
struct data {
  int nr;
  char const *value;
} dat[] = {
  {1, "Foo"}, {2, "Bar"}, {3, "Hello"}, {4, "World"}
};
 
int data_cmp(void const *lhs, void const *rhs) {
  struct data const *const l = lhs;
  struct data const *const r = rhs;
  return l->nr < r->nr;
}
 
int main(void) {
  struct data key = { .nr = 3 };
  struct data const *res = bsearch(&key, dat, sizeof(dat)/sizeof(dat[0]),
                                   sizeof(dat[0]), data_cmp);
  if(!res) {
    printf("No %d not found\n", key.nr);
  }
  else {
    printf("No %d: %s\n", res->nr, res->value);
  }
}

出力:

No 3: Hello

参照

不特定の型の要素の範囲をソートします
(関数) [edit]