c/c++笔试面试经典函数实现

 /* strcpy函数实现 拷贝字符串 */
char* Strcpy(char* dst, char* src)
{
assert(dst != NULL && src != NULL); // 断言 dst和src不能为NULL char* dst_address = dst; // 保存目的地址 while((*(dst++) = *(src++)) != '\0')
{
/* do nothing */
} return dst_address; // 返回目的地址 允许链式表达式
} /* strncpy函数实现*/ char* Strncpy(char* dst, const char* src, size_t num)
{
assert(dst != NULL && src != NULL); // 断言 dst和src不能为NULL char* dst_address = dst; size_t i = ; // 控制复制的个数
while(i++ < num && (*dst++ = *src++) != '\0')
{
/* do nothing */
} if(*dst != '\0') // 字符必须以'\0'结尾
{
*dst = '\0';
} return dst_address;
} size_t Strlen(const char *str)
{
assert(str != NULL); int count = ; while(*str++ != '\0')
{
++count;
} return count;
} void* Memcpy( void *dest, const void *src, size_t count )
{
assert(dest != NULL && src != NULL); char* _dest = (char*)dest;
char* _src = (char*)src; while (count--)
{
*_dest++ = *_src++;
} return dest;
} void * Memmove ( void * destination, const void * source, size_t num )
{
char* _dst = NULL;
char* _src = NULL; if(destination <= source)
{
_dst = destination;
_src = source; while (num--)
{
*_dst++ = *_src++;
}
}
else
{
_dst = destination;
_src = source; _dst += num;
_src += num; while (num--)
{
*--_dst = *--_src;
}
}
}
 int FibonacciSequence(unsigned int n)
{
if( == n || == n)
{
return n;
}
else
{
return FibonacciSequence(n-)+FibonacciSequence(n-);
}
}
 int BinSearch(int* arr, int left, int right, int key)
{
if(!arr)
{
return -;
} while (left <= right)
{
int mid = left + ((right - left) >> ); if(arr[mid] < key)
{
left = mid + ;
}
else if(arr[mid] > key)
{
right = mid - ;
}
else
{
return mid;
}
}
return -;
}
 // 插入排序
void InsertionSort(int* arr, int len)
{
for(int j = ; j < len; ++j)
{
int i = j - ;
int key = arr[j]; while(i >= && a[i] > key)
{
a[i+] = a[i];
--i;
}
arr[i+] = key;
}
}
 int Partition(vector<int>& vec, int low, int up)
{
int pivot = vec[up];
int i = low - ; for(int j = low; j < up; ++j)
{
if(vec[i] < pivot)
{
++i;
std::swap(vec[i], vec[j]);
}
}
std::swap(vec[i+], vec[up]); return i+;
} void QuickSort(vector<int>& vec, int low, int up)
{
if(low < up)
{
int mid = Partition(vec, low, up); QuickSort(vec, low, mid - );
QuickSort(vec, mid + , up);
}
} void Sort(vector<int>& vec)
{
QuickSort(vec, , vec.size() - );
}
template <typename T>
int BinSearch(std::vector<T>& array, T key)
{
int left = ;
int right = array.size(); while (left < right)
{
int mid = (left + right) >> ; // 中点 if (array[mid] < key)
{
left = mid;
}
else if (key < array[mid])
{
right = mid;
}
else
{
return mid;
}
} return -; // 查找失败
}
上一篇:CSS3中的伪类选择器详解


下一篇:【CSS3】---结构性伪类选择器-first-child+last-child