练习使用STL中vector以及algorithm…

来源:互联网 发布:如何隐藏域名信息 编辑:程序博客网 时间:2024/06/09 17:04
// TestSTL.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<vector>//头文件vector,含有向量相关函数
#include<algorithm>//头文件algorithm,含有算法相关函数
#include<functional>
using namespace std;

class myclass
{
public:
//构造函数
int first;
int second;
myclass(int a,int b):first(a),second(b)
{}

bool operator < (const myclass&m)const //引用,常量
{
return first < m.first;
}
};//定义myclass,并且重载了‘<’运算符,用于之后的排序算法sort调用

//比较方法
bool less_second(const myclass &m1,constmyclass &m2)
{
return m1.second < m2.second; //根据第二元素判断
}

int _tmain(int argc, _TCHAR* argv[])
{
vector vect;//创建对象vect
int i;//c++中for声明的变量在for函数的范围内有效
for(i = 0;i<10;i++)
{
myclass my(10-i,3*i);//创建对象并初始化
vect.push_back(my);//写入vect容器内
}

//输出未排序的向量
for(i = 0;i
{
cout<<"("<<vect[i].first<<","<<vect[i].second<<")"<<endl;
}

//调用排序算法对容器中的向量进行排序
sort(vect.begin(),vect.end());
cout<<"After sorted byfirst:"<<endl;
for(i = 0;i
{
cout<<"("<<vect[i].first<<","<<vect[i].second<<")"<<endl;
}

//以第二元素为关键字调用排序算法
sort(vect.begin(),vect.end(),less_second);//调用自定义的比较算法进行排序
cout<<"After sorted bysecond:"<<endl;
for(i = 0;i
{
cout<<"("<<vect[i].first<<","<<vect[i].second<<")"<<endl;
}
getchar();
return 0;
}

0 0
原创粉丝点击