《我的第一本c++书》学习笔记:STL的一个简单例子

代码如下:

// k.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <functional>


using namespace std;

class Student
{
public:
	Student()
	{
		m_strName = "";
		m_nHeight = 0 ;
	};
	Student(string strName, int nHeight)
		: m_strName(strName) , m_nHeight(nHeight)
	{

	}
public:
	int GetHeight()
	{
		return m_nHeight;
	}
	void ReportName()
	{
		cout<<"姓名: "<<m_strName<<"\t身高:"<<m_nHeight<<endl;
	}
private:
	string m_strName;
	int m_nHeight;
};


bool sortByHeight(Student st1, Student st2)
{
	return st1.GetHeight() < st2.GetHeight() ; 
}

int _tmain(int argc, _TCHAR* argv[])
{
	Student st1("Zhouzhou",173);
	Student st2("Yichen",163);
	Student st3("Shiye",187);

	vector<Student> vecStu;
	vecStu.push_back( st1 );
	vecStu.push_back( st2 );
	vecStu.push_back( st3 );

	/*STL的标准算法是不支持传入一个“成员函数指针”的(因为当没有实例化的对象的时候,成员函数根本不知道this是谁),
	但是支持“普通函数指针”或“仿函数”,而mem_fun、mem_fun_ref的作用就是将一个"成员函数指针"包装成一个仿函数。
	std::mem_fun和std::mem_fun_ref所实现的是相同的功能,可以这么理解之间的差异,mem_fun用于处理容器对象指针,
	而mem_fun_ref用于处理容器对象实体。*/
	sort(vecStu.begin(), vecStu.end(), sortByHeight);
	
	for_each( vecStu.begin(), vecStu.end(), mem_fun_ref(&Student::ReportName) );
	
	
	

	return 0;
}

如果容器中有冗余,则需要调用unique()算法来删除,注意,这里unique只能移除相邻的重复元素,比如(10020500)删除后(102050),如果想移除所有相同的元素,则必须先排序(00000125),删除后(0125)。

unique()算法删除容器中的冗余元素之后,返回值为指向正确数据的后一位。

如果vector中存储的元素是自定义的结构或者是类,那么就需要重载操作符,根据类的某一个成员变量排序或者比较。 
 
sort算法需要重载"<"操作符。 
unique算法需要重载"=="操作符。 

代码如下:

// k.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <functional>


using namespace std;

class Student
{
public:
	Student()
	{
		m_strName = "";
		m_nHeight = 0 ;
	};
	Student(string strName, int nHeight)
		: m_strName(strName) , m_nHeight(nHeight)
	{

	}
	bool operator == (Student& st)
	{
		return m_strName == st.GetName() && m_nHeight == st.GetHeight(); 
	}
public:
	int GetHeight()
	{
		return m_nHeight;
	}
	string GetName()
	{
		return m_strName;
	}

private:
	string m_strName;
	int m_nHeight;
};


bool sortByHeight(Student st1, Student st2)
{
	return st1.GetHeight() < st2.GetHeight() ; 
}

int _tmain(int argc, _TCHAR* argv[])
{
	Student st1("Zhouzhou",173);
	Student st2("Yichen",163);
	Student st3("Zhouzhou",173);
	Student st4("ZH",183);

	vector<Student> vecStu;
	vecStu.push_back( st1 );
	vecStu.push_back( st2 );
	vecStu.push_back( st3 );
	vecStu.push_back( st4 );

	
	sort(vecStu.begin(), vecStu.end(), sortByHeight);
	
	vector<Student>::iterator it = unique(vecStu.begin(), vecStu.end());

	vecStu.erase(it, vecStu.end());
	
	

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值