STL自定义类型

// Student.h: interface for the Student class.

//

//////////////////////////////////////////////////////////////////////

 

#include <iostream>  

#include <vector>  

#include <algorithm> 

#include <functional>

using namespace std;

 

 

 

#if !defined(AFX_STUDENT_H__A128B9F0_66AE_4C4C_B99F_970C1C5BB355__INCLUDED_)

#define AFX_STUDENT_H__A128B9F0_66AE_4C4C_B99F_970C1C5BB355__INCLUDED_

 

#if _MSC_VER > 1000

#pragma once

#endif // _MSC_VER > 1000

 

 

class Student;

ostream& operator<<(ostream& os,const Student& _Student);

bool operator<(const Student& s1, const Student& s2);

// 由于编译器本身的问题,重载运算符的函数做友元的时候要先声明一下

// (此说法来自互联网),没有权威的说明,但是确实的这样,你可以看到

// test函数和myless类都没有任何问题

 

 

 

class Student 

{

public:

         Student();

         virtual ~Student();

 

private:

 char   name[32];

 int    goal;

public:

 Student(char *_name, int _goal)

 {

  strcpy(name, _name);

  goal = _goal;

 }

 

// 友元函数声明

friend static bool operator<(const Student& s1, const Student& s2);

friend static ostream& operator<<(ostream& os,const Student& _Student);

friend class myless;

friend static 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;

 }

 

 

 

};

 

#endif // !defined(AFX_STUDENT_H__A128B9F0_66AE_4C4C_B99F_970C1C5BB355__INCLUDED_)

  

 

Main函数:

 

#include <iostream>  

#include <vector>  

#include <algorithm> 

#include <functional>

#include "Student.h"

using namespace std;

 

 

int main(int argc, char* argv[])

{

         printf("Hello World!\n");

 

         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;

 

 

  

posted @ 2012-05-16 17:38  乌托邦.  阅读(271)  评论(0)    收藏  举报