#include <iostream>
#include <cstdarg> //for va_list, va_start, va_arg, va_end
#include <memory> //for uninitialize_copy,...
#include <algorithm>
template<typename T>
void Print(T *a, size_t n)
{
for(size_t i = 0; i < n; ++i)
std::cout << a[i] << " ";
std::cout << std::endl;
}
//可变参数列表
void ChangeableArgs(int n, ...)
{
int sum = 0;
va_list vl;
va_start(vl, n);
for(int i = 0;i < n;++i)
sum += va_arg(vl, int);
va_end(vl);
std::cout << n << " sum is = " << sum << std::endl;
}
int compare(const void *a, const void *b)
{
int *pa = (int*)a;
int *pb = (int*)b;
return ((*pa) > (*pb) ? 0 : 1);
}
int main()
{
//可变参数列表测试
ChangeableArgs(0);
ChangeableArgs(2, 5, 8);
ChangeableArgs(5, 2, 5, 7, 9, 14);
ChangeableArgs(9, 1, 2, 3, 4, 5, 6, 7, 8, 9);
std::cout << std::endl;
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int sizeLen = sizeof arr / sizeof arr[0];
int *pArr = new int[sizeLen];
//把一个对象copy到另外一个对象中
/*
template<class InputIterator, class ForwardIterator>
ForwardIterator uninitialized_copy(
InputIterator _First,
InputIterator _Last,
ForwardIterator _Dest
);
*/
std::uninitialized_copy(arr, arr + sizeLen, pArr);
Print(pArr, sizeLen);//1 2 3 4 5 6 7
//将某个对象中的数据全部设为value
/*
template<class ForwardIterator, class Type>
void uninitialized_fill(
ForwardIterator _First,
ForwardIterator _Last,
const Type& _Val
);
*/
std::uninitialized_fill(pArr, pArr + sizeLen, 5);
Print(pArr, sizeLen);//5 5 5 5 5 5 5
//将某个对象中的n个数据设为value
/*
template<class FwdIt, class Size, class Type>
void uninitialized_fill_n(
ForwardIterator _First,
Size _Count,
const Type& _Val
);
*/
std::uninitialized_fill_n(pArr, 3, 1);
Print(pArr, sizeLen);// 1 1 1 5 5 5 5
std::cout << std::endl;
//sort:
//两个参数为迭代器,具有随机访问的功能
//第二个版本的第三个参数为一个函数指针,
//(1)可以忽略,则默认为从小到大排序;
//(2)可以使用标准库里的std::greater<T>(),使用从大到小排序
//(3)也可以自定义函数,作为参数
/*
template<class RandomAccessIterator>
void sort(
RandomAccessIterator _First,
RandomAccessIterator _Last
);
template<class RandomAccessIterator, class Pr>
void sort(
RandomAccessIterator _First,
RandomAccessIterator _Last,
BinaryPredicate _Comp
);
*/
int b[] = {23, 67, 35, 90, 82, 19, 56, 48};
std::sort(b, b + sizeof b / sizeof b[0]);
Print(b, sizeof b / sizeof b[0]);
//qsort的第三个参数为函数指针,接收两个void类型的指针,所以需要自定义函数
/*
void qsort(
void *base,
size_t num,
size_t width,
int (__cdecl *compare )(const void *, const void *)
);
*/
qsort(b, sizeof b / sizeof b[0], sizeof b[0], compare);
Print(b, sizeof b / sizeof b[0]);
return 0;
}
====================打个广告,欢迎关注====================
QQ: | 412425870 |
csdn博客: | http://blog.csdn.net/caychen |
码云: | https://gitee.com/caychen/ |
github: | https://github.com/caychen |
点击群号或者扫描二维码即可加入QQ群: | |