关于stl 的sort函数
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool pr(int s1, int s2)
{
return s1>s2;
}
int main(int argc, char* argv[])
{
vector<int> vec;
vector<int>::iterator i;
vec.push_back (10);
vec.push_back (3);
vec.push_back (7);
sort(vec.begin(), vec.end(),pr); // Sort the vector
for (i = vec.begin(); i != vec.end(); i++)
{
cout<<*i<<endl;
}
return 0;
}
/////////////////////////////////////////////////
/////////////////////////////////////////////////
急急急! 我早就有的一个问题是:
sort(vec.begin(), vec.end())这一句不是就能实现一组数的从大到小排列吗?
那还要bool 型的函数pr()有什么用?
麻烦路过的高手详解一下,谢谢了!
[解决办法]
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool pr(int s1, int s2)
{
return s1<s2;
}
int main(int argc, char* argv[])
{
vector<int> vec;
vector<int>::iterator i;
vec.push_back (10);
vec.push_back (3);
vec.push_back (7);
sort(vec.begin(), vec.end(),pr); // Sort the vector
for (i = vec.begin(); i != vec.end(); i++)
{
cout<<*i<<endl;
}
return 0;
}
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
vector <int>vec;
vector <int>::iterator iter;
vec.push_back(10);
vec.push_back(3);
vec.push_back(7);
sort(vec.begin(), vec.end(), std::greater<int>());
for (iter = vec.begin(); iter != vec.end(); ++iter) {
cout << *iter << endl;
}
return 0;
}