关于利用STL中的sort算法对向量等容器进行排序的问题
2013-09-13 23:10
591 查看
使用该算法需要包含头文件#include <algorithm>; 并且声明命名空间usingnamespace std;.
该算法默认是按照由小到大排序的,如果需要由大到小排序,那么有两种办法:(1)假设有向量vector<int> v;可以先使用sort排序,即sort(v.begin(), v.end());然后再逆序即可,即reverse(v.begin(),v.end());这个方法会耗时更多,因为多了一次逆序的操作。(2)方法2就是直接进行由大到小排序,这时需要自己定义比较函数(不管向量中的数据是否为基本数据类型,非基本数据类型不管是由小到大,还是想由大到小都必须自己定义比较函数)。
例子:
#include
"stdafx.h"
#include
<iostream>
#include
<vector>
#include
<algorithm>
using namespace std;
//注意:自定义的比较函数原型为:bool
函数名(类型1 参数1,类型1 参数2);如果返回false那么就需要调换数据的位置,如果返回true,则不用调换。
boolcmpMy(const
int&nFirst,const
int&nSecond)
{
if(nFirst <= nSecond) //由大到小排序
{
return
false;
}
return
true;
}
int_tmain(int argc, _TCHAR* argv[])
{
vector<int> v;
int n=5;
cout<<"请输入"<<n<<"个整数"<<endl;
int i=0;
int nValue;
while(i<n)
{
cin>>nValue;
v.push_back(nValue);
++i;
}
cout<<"排序前的结果:"<<endl;
for(int i=0; i<n;++i)
{
cout<<v[i]<<endl;
}
//sort(v.begin(),v.end()); //默认按从小到大排序
sort(v.begin(),v.end(),cmpMy);//利用自己定义的比较函数变为由大到小排序
cout<<"排序后的结果:"<<endl;
for(int i=0; i<n;++i)
{
cout<<v[i]<<endl;
}
reverse(v.begin(),v.end());//逆序
cout<<"逆序后的结果:"<<endl;
for(int i=0; i<n;++i)
{
cout<<v[i]<<endl;
}
}
输出结果:
该算法默认是按照由小到大排序的,如果需要由大到小排序,那么有两种办法:(1)假设有向量vector<int> v;可以先使用sort排序,即sort(v.begin(), v.end());然后再逆序即可,即reverse(v.begin(),v.end());这个方法会耗时更多,因为多了一次逆序的操作。(2)方法2就是直接进行由大到小排序,这时需要自己定义比较函数(不管向量中的数据是否为基本数据类型,非基本数据类型不管是由小到大,还是想由大到小都必须自己定义比较函数)。
例子:
#include
"stdafx.h"
#include
<iostream>
#include
<vector>
#include
<algorithm>
using namespace std;
//注意:自定义的比较函数原型为:bool
函数名(类型1 参数1,类型1 参数2);如果返回false那么就需要调换数据的位置,如果返回true,则不用调换。
boolcmpMy(const
int&nFirst,const
int&nSecond)
{
if(nFirst <= nSecond) //由大到小排序
{
return
false;
}
return
true;
}
int_tmain(int argc, _TCHAR* argv[])
{
vector<int> v;
int n=5;
cout<<"请输入"<<n<<"个整数"<<endl;
int i=0;
int nValue;
while(i<n)
{
cin>>nValue;
v.push_back(nValue);
++i;
}
cout<<"排序前的结果:"<<endl;
for(int i=0; i<n;++i)
{
cout<<v[i]<<endl;
}
//sort(v.begin(),v.end()); //默认按从小到大排序
sort(v.begin(),v.end(),cmpMy);//利用自己定义的比较函数变为由大到小排序
cout<<"排序后的结果:"<<endl;
for(int i=0; i<n;++i)
{
cout<<v[i]<<endl;
}
reverse(v.begin(),v.end());//逆序
cout<<"逆序后的结果:"<<endl;
for(int i=0; i<n;++i)
{
cout<<v[i]<<endl;
}
}
输出结果:
相关文章推荐
- 利用STL中的sort算法对向量等容器进行排序
- 今天遇到一个关于STL中排序的问题, 怀疑是sort的bug!
- 练习使用 STL sort 对容器进行排序
- 如何利用C++ vector的sort算法对元素是自定义类型进行排序
- 用Array.Sort对字符串进行排序的问题
- Android利用Collections.sort()对Map里的键值对按照键进行排序,让listview按序显示
- STL_算法_局部排序(partial_sort、partial_sort_copy)
- C++利用stl::sort对结构体数组中的字符串成员排序
- C++学习笔记26——泛型算法之容器元素排序(sort unique)
- 实现一个简单的c++ list容器(含sort排序 链表归并算法实现)
- 利用STL算法高效实现容器的循环移位
- STL的list容器如何对结构体进行排序
- 链表的归并排序:来自STL_ list_ sort 算法
- C# 利用list.sort()进行排序
- 对vector等STL标准容器进行排序操作
- 利用 Arrays.sort 字符串 进行排序 完全按字符 排序 忽略字符大小写
- 关于SVM中SMO算法第一个向量选择的问题
- 利用 Arrays.sort 字符串 进行排序 完全按字符 排序 忽略字符大小写
- C++ 中list容器,自定义sort排序规则,stl中sort自定义排序规则
- 对vector等STL标准容器进行排序操作