#include <iostream>
#include <cstring>
void function1(); //实现交换两个元素内容的函数swap演示
void function2(); //在数组array中查找key元素并返回其索引的演示
void swap1(int *ipa, int *ipb);
void swap2(void *vp1, void *vp2, int size);
int lsearch1(int key, int array[], int size);
void *lsearch2(void *key, void *base, int n, int elemSize);
int main()
{
//function1();
function2();
return 0;
}
void function1()
{
int a = 1, b = 2;
int *pa = &a, *pb = &b;
//swap前
std::cout << "*pa = " << *pa << "; "
<< "*pb = " << *pb
<< std::endl;
swap1(pa, pb);
//swap2(pa, pb, sizeof(int));
//swap后
std::cout << "*pa = " << *pa << "; "
<< "*pb = " << *pb
<< std::endl;
}
void function2()
{
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int key, size = 10;
std::cout << "input a key: ";
std::cin >> key;
int ret = lsearch1(key, array, size);
if (ret < 0) {
std::cout << "error!!!" << std::endl;
}
else
{
std::cout << "index: " << ret << std::endl;
}
int *pkey = &key;
int *pret = (int *)lsearch2(pkey, array, size, sizeof(int));
std::cout << "*pret = " << *pret << std::endl;
}
void swap1(int *ipa, int *ipb)
{
int temp = *ipa;
*ipa = *ipb;
*ipb = *ipa;
}
void swap(void *vp1,void *vp2, int size)
{
char buffer[size];
memcpy(buffer, vp1, size);
memcpy(vp1, vp2, size);
memcpy(vp2, buffer, size);
}
int lsearch1(int key, int array[], int size)
{
for (int i = 0; i < size; i++) {
if (array[i] == key) {
return i+1;
}
}
return -1;
}
void *lsearch2(void *key, void *base, int n, int elemSize)
{
for (int i = 0; i < n; i++) {
void *elemAddr = (char *)base + i*elemSize;
if(memcmp(key, elemAddr, elemSize) == 0)
return elemAddr;
}
return NULL;
}