随着练习代码的习题数量的增加,意识到了自己和系统学习c++的人之间还有很大的差距。今天学习的是sort函数,它是STL中可以直接调用的排序类函数,以下是我从另一篇博客中摘取的,自己用起来简单顺手的部分。
1.要使用sort函数只需用#include <algorithm> 即可使用,语法描述为:
sort(begin,end),表示一个范围,例如:
int main()
{
int a[10] = { 2,4,1,23,5,76,0,43,24,65 }, i;
for (i = 0; i<10; i++)
cout << a[i] <<" ";
cout << endl;
sort(a, a + 10);
for (i = 0; i<10; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
输出结果将是把数组a按升序排序。
2.sort中增加一个参数,可升序可降序。
int main()
{
int a[10] = { 2,4,1,23,5,76,0,43,24,65 }, i;
for (i = 0; i<10; i++)
cout << a[i] <<" ";
cout << endl;
sort(a, a + 10,compare);
for (i = 0; i<10; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
1)自己编写compare函数:
bool compare(int a,int b)
{
return a<b; //升序排列,如果改为return a>b,则为降序
}
2)接着调用三个参数的sort:sort(begin,end,compare)就成了。对于list容器,这个方法也适用,把compare作为sort的参数就可以了,即:sort(compare).
3.标准库里已经有现成的了,就在functional里,include进来就行了。functional提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>。对于这个问题来说,greater和less就足够了,直接拿过来用:
- 升序:sort(begin,end,less<data-type>());
- 降序:sort(begin,end,greater<data-type>()).
int main()
{
int a[10] = { 2,4,1,23,5,76,0,43,24,65 }, i;
for (i = 0; i<10; i++)
cout << a[i] <<" ";
cout << endl;
sort(a, a + 10,less<int>());
for (i = 0; i<10; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
以上三种方式对于我目前的水平来说已足够,以后会更加深入的学习。