qsort()整理以及对函数指针的使用
1.关于qsort()函数总结;
同类型数据的排序可以调用函数库<cstdlib>(C++重写)或者<stdlib>中qsort()函数.
函数原型
void qsort (void* base, size_t num, size_t size,
int (*compar)(const void*,const void*));
base:空指针指向待排序的数组;
num:排序元素个数;
size:元素占位大小;
compare:函数指针。
在使用qsort()函数时,首先需要编写 比较函数compar 的实现
int compareMyType (const void * a, const void * b) { if ( *(MyType*)a < *(MyType*)b ) return -1; if ( *(MyType*)a == *(MyType*)b ) return 0; if ( *(MyType*)a > *(MyType*)b ) return 1; }
或者
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
使用方法:
int values[] = { 40, 10, 100, 90, 20, 25 };
qsort (values, 6, sizeof(int), compare);
PS:C++中可使用<algorithm>中函数sort();
default (1) template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); custom (2) template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
使用方法:参数first与second为迭代器参数,compare为函数.
bool myfunction (int i,int j) { return (i<j); } struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject; int main () { int myints[] = {32,71,12,45,26,80,53,33}; std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33 // using default comparison (operator <): std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33 // using function as comp std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80) // using object as comp std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
2.有关函数指针的使用总结;
函数指针是指向函数的指针变量。 因而“函数指针”本身首先应是指针变量,只不过该指针变量指向函数。
函数名本身代表指针
如下程序(网络所得):
#include<stdio.h> int Function(int Num); int main(void) { int (*P_Fun)(int) = &Function; int a; a = Function(25); printf("%d\n", a); a = (*P_Fun)(25); printf("%d\n", a); a = P_Fun(25); printf("%d\n", a); return 0; } //... int Function(int Num) { int result; result = Num * 2; return result; }
运行结果,三种调用的输出是相同的. (*P_Fun)(25)与P_Fun(25)都能够正常调用函数。
因为函数名本身就能指向函数体,函数指针不同于一般变量,默认找到指向的函数入口地址,我觉得编译器会默认的进行指针操作.
浙公网安备 33010602011771号