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;

 

 

  

转载于:https://www.cnblogs.com/totem1990/archive/2012/05/16/2504386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值