当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

自定义函数使用map排序

 #pragma warning(disable:4786)
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;

/* 从小到大排序 */
struct ltstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) < 0;
}
};
typedef map<const char*, int,ltstr> MYDATAMAP;
typedef MYDATAMAP::iterator Itermydata;

int main(int argc, char* argv[])
{
MYDATAMAP mydata;
mydata.insert(Itermydata::value_type("3",9));
mydata.insert(Itermydata::value_type("4",9));
mydata.insert(Itermydata::value_type("1",9));
mydata.insert(Itermydata::value_type("2",9));
Itermydata begin = mydata.begin();
for(; begin != mydata.end(); ++begin)
{
cout<<"Key: " << begin->first
<<" Value: " << begin->second <<endl;
}
mydata.clear();
return 0;
}

    结果输出为:

    Key: 1 Value: 9

    Key: 2 Value: 9

    Key: 3 Value: 9

    Key: 4 Value: 9

相关内容
赞助商链接