cplusplus

使用STL排序算法排序自定义类

上一篇 / 下一篇  2011-08-20 15:36:13 / 个人分类:C++

是使用STL的sort排序自己的类,其实就是传入sort的第三个参数,具体由三种方法,分别是:

1.定义普通函数

2.定义函数对象

3.重载 "<"

代码如下:

定义排序函数:
bool Less(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //可以自己设定
}

std::sort(sutVector.begin(), stuVector.end(), Less);

重载 "<"

bool operator<(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //可以自己设定
}
std::sort(sutVector.begin(), stuVector.end());

定义函数对象

struct Less
{
bool operator()(const Student& s1, const Student& s2)
{
return s1.name < s2.name; //可以自己设定
}
};

std::sort(sutVector.begin(), stuVector.end(), Less());

 

=======================================================================================

下面是个完整的Demo:已编译通过

#include <iostream>  
#include <vector>  
#include <algorithm> 
#include <functional>
using namespace std;

class Student;
ostream& operator<<(ostream& os,const Student& _Student);
bool operator<(const Student& s1, const Student& s2);
// 由于编译器本身的问题,重载运算符的函数做友元的时候要先声明一下
// (此说法来自互联网),没有权威的说明,但是确实的这样,你可以看到
// test函数和myless类都没有任何问题


class Student {
private:
 char   name[32];
 int    goal;
public:
 Student(char *_name, int _goal)
 {
  strcpy(name, _name);
  goal = _goal;
 }

// 友元函数声明
friend bool operator<(const Student& s1, const Student& s2);
friend ostream& operator<<(ostream& os,const Student& _Student);
friend class myless;
friend bool test(const Student& s1);
};

bool test(const Student& s1)
{
 cout<< s1.goal << endl;
 return true;
}

// 重载"<"实现泛型算法sort
bool operator<(const Student& s1, const Student& s2)
{
 return s1.goal < s2.goal;
}


// 重载输出流迭代子
ostream& operator<<(ostream& os,const Student& _Student)
{
 os<<_Student.name<<"    "<<_Student.goal;
 return os;
}

// 函数对象,用于升序排列
class myless
{
public:
 bool operator()(const Student& s1, const Student& s2)
 {
  return s1.goal > s2.goal;
 }
};


int main()
{
 
 vector<Student> col1;
 ostream_iterator< Student > output( cout, "\n" );
 
 Student A1("xiao1", 99);
 Student A2("xiao2", 23);
 Student A3("xiao3", 53);

 col1.push_back(A1);
 col1.push_back(A2);
 col1.push_back(A3);
 
 
 cout << "Vector col1 contains: \n";
 copy( col1.begin(), col1.end(), output );   // 输出初始列表容器col1中的元素
 sort(col1.begin(),col1.end());    // 第一种调用形式
 cout << "\nAfter sorted in ascending order col1 contains: \n";
 copy( col1.begin(), col1.end(), output ); // 升序排序元素后列表容器col1中的元素
 sort(col1.begin(),col1.end(),myless());     // 第二种调用形式使用标准函数对象
 cout << "\nAfter sorted in descending ordercol1 contains: \n";
 copy( col1.begin(), col1.end(), output );   // 降序排序元素后列表容器col1中的元素
 cout<<endl;

 col1.clear();

 return 0;
}

http://hi.baidu.com/fu9805/blog/item/65c956acb70347114a36d627.html


TAG:

 

评分:0

我来说两句

Open Toolbar