#include <cstdlib>
#include <iostream>
using namespace std;
// C++ standard has context as third parameter.
// MSVS 2017 has it as the first.
// int compareInt(const void * pLeft, const void * pRight, void * context)
int compareInt(void * context, const void * pLeft, const void * pRight)
{
if (*(const int *)pLeft < *(const int *)pRight)
{
return -1;
}
else if (*(const int *)pLeft > *(const int *)pRight)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int list[5] = {5, 4, 2, 3, 1};
qsort_s(list, sizeof(list)/sizeof(int), sizeof(int), compareInt, NULL);
for (int i : list)
{
cout << i << " ";
}
int key = 3;
int * keyPointer = (int *)bsearch_s(&key ,
list ,
sizeof(list)/sizeof(int),
sizeof(int) ,
compareInt ,
NULL );
cout << ": " << (keyPointer - list);
cout << endl;
return 0;
}
// Output: 1 2 3 4 5 : 2
References:http://en.cppreference.com/w/c/algorithm/qsort
http://en.cppreference.com/w/c/algorithm/bsearch
No comments:
Post a Comment