Re: 关于 stl 和 c++ 的一点问题

楼主: firejox (Tangent)   2018-11-30 23:25:23
lambda的出现不只是趋势,也是一个需求。以排序来说好了。
不管要排序什么样的资料,会有差异的也只有比较的部份。然后
C有qsort、C++有std::sort可以用。
C的qsort如下:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
要用qsort 去排一个 int arr[] = {5, 4, 1, 3, 2} 的阵列,就需要
定义一个函数
int cmp(const void *a, const void *b) {
return (const int*)a - *(const int*)b;
}
然后这样 qsort(arr, 5, sizeof(int), cmp);
C++98的时候,std::sort 让排序比qsort更直观了。而且多了一个方式
传比较函式。你可以overload operator来传比较函式。
struct CompareInt {
bool operator() (const int &a, const int &b) const {
return a < b;
}
} cmp;
std::sort(a, a + 5, cmp);
然而这样还是有个问题,如果是小程式,写1、2个比较函式到还好。
如果有很多不一样的比较函式要写就会是个麻烦,所以才需要lambda。
有了lambda你可以这样写
std::sort(a, a + 5, [](const int &a, const int &b) { return a < b; });
如此一来,你可以解决命名的问题以及可以比较直观。

Links booklink

Contact Us: admin [ a t ] ucptt.com