구조체 배열이 있습니다. 그것을 호출 할 수 있습니다 structsarray
배열을 C로 정렬
그리고 int ints의 배열은 stuct의 인덱스입니다. 나는 indexarray
를 정렬하고 싶습니다하지만 난 그 설치를 수행 할 수있는 int
structsarray
에서 어떤 방법으로 정렬 비교하려는 것이 indexarray
전화를하자?
구조체 배열이 있습니다. 그것을 호출 할 수 있습니다 structsarray
배열을 C로 정렬
그리고 int ints의 배열은 stuct의 인덱스입니다. 나는 indexarray
를 정렬하고 싶습니다하지만 난 그 설치를 수행 할 수있는 int
structsarray
에서 어떤 방법으로 정렬 비교하려는 것이 indexarray
전화를하자?
당신은 비교 기능이 이와 같은 :
int my_compare(const void *a, const void *b)
{
int index1 = *((const int *) a);
int indexb = *((const int *) b);
return structsarray[index1].field - structsarray[index2].field;
}
인수는 정렬 된 배열의 값으로 포인터입니다. 상수 void 포인터를 상수 int 포인터로 캐스팅 한 다음 해당 포인터를 역 참조하여 실제 값을 가져옵니다.
그러나 어떻게 든 structsarray'에 대한 포인터를 매개 변수로 전달할 수 있습니까? – nkobber
@Razcou'structsarray'를'qsort'에 넘겨 주면 비교 함수는 구조체에 대한 두 개의 포인터를 얻습니다. 'struct my_struct * struct1 = (struct my_struct *) a;' –
자체 비교 기능을 구현하여 qsort를 사용할 수 있습니다. 여기가 설명 : http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
제공되는 정보는 매우 제한되어 있습니다.
알고리즘 예 : 거품 종류 : 다음과 같이 당신이 할 수있는 수 있음
for (c = 0 ; c < (n - 1); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (index[d] > index[d+1]) /* For decreasing order use < */
{
/* Sort index */
swap = index[d];
index[d] = index[d+1];
index[d+1] = swap;
/* Sort struct using above index */
swap = struct[d];
struct[d] = struct[d+1];
struct[d+1] = swap;
}
}
}
http://mattgemmell.com/2008/12/08/what-have-you-tried/ –