| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 701 人关注过本帖
标题:“游乐园”进,关于map.
只看楼主 加入收藏
aipb2007
Rank: 8Rank: 8
来 自:CQU
等 级:贵宾
威 望:40
帖 子:2879
专家分:7
注 册:2007-3-18
收藏
 问题点数:0 回复次数:2 
“游乐园”进,关于map.

这是先前你写的,按关键字排序(数位和)。

#include<map>
#include<iostream>

using namespace std;

class Compare {//用来对关键字进行排序
public:

bool operator()( int key1, int key2 ) const {
return key1<=key2?1:0;
}
};

int sum(int n)//计算各位之和
{
int sum=0;
while(n)
{
sum+=n%10;
n/=10;
}
return sum;
}

int main()
{
int a[6]={123,45,67,2222,96,9};//给定的数组
copy(a,a+6,ostream_iterator<int>(cout," ")); //输出最初的数组
map<int,int,Compare> s;
for(int i=0;i<6;++i) s[sum(a[i])]=a[i]; //按照关键字排序赋值
cout<<"\nAfter Sorted:\n";
for( map<int,int,Compare>::iterator iter = s.begin(); iter != s.end(); iter++ ) cout <<(*iter).second<<" ";//输出"排序"后的数组
cout<<endl;

return 0;
}

恰好我这两天学到 map,我看了下,有些地方不懂!

你上面用到的map怎么有3个参数,3的个参数是???
还有,键是不能重复的,你怎么做到那点?
为什么要有个compare的类,重载()有什么用?代码中哪里用了?

谢谢。

我也用map写了个处理这个问题,你看看,跟你那个不同,你那个我不明白,你讲解下

#include <map>
#include <iostream>

using namespace std;

const int size = 10;
int convert(int); //求数位和
int main(){
map<pair<int,int>,int> sort;
int a[size] = {125,224,56,4,2531,12369,11111,457,902,325}; //原始数组
cout << "before sorted\n";
for (int i = 0;i < size;++i){
cout << a[i] << " ";
sort[make_pair(convert(a[i]),i)] = a[i]; //关键字排序
}
cout << "\b" << endl;
map<pair<int,int>,int>::iterator p = sort.begin();
cout << "\nafter sorted\n";
for (;p != sort.end();++p) //输出排序后数组
cout << p->second << " ";
cout << "\b" << endl;

system("pause");
return 0;
}

int convert(int val){
int sum = 0;
while (val != 0){
sum += val % 10;
val /= 10;
}
return sum;
}





[此贴子已经被作者于2007-4-22 16:07:56编辑过]

搜索更多相关主题的帖子: 游乐园 map 
2007-04-22 16:06
游乐园
Rank: 3Rank: 3
等 级:新手上路
威 望:6
帖 子:671
专家分:0
注 册:2006-11-1
收藏
得分:0 
嗯 呵呵 我那个写的有点多余了 那天没注意 平时比较的都字符串的多 忘了map本身就能排序了 完全可以不调用那个Compare 但第三个参数也狠有用的


map 一般不是提供两个参数嘛 如map<K, V> ,K和V就是键与其对应的值. map存储过程中本身已经对键按照"<" 的关系进行了比较过了

可是 " < "符号用来判断普通的键(数值型)可以,但如果是char [] 型的 只能调用strcmp()<0 来比较了 所以就涉及到map里的第三个参数 map<K,V,comp_fun>

第三个参数是个比较函数,如果指明了第三个参数具体后 ,在存储的时候 键之间就按所提供的比较函数进行比较 默认调用应该是comp_fun(K1,K2) ,因为是类嘛所

以对()重载了 剩下的 和你写的就一样咯

unicorn-h.spaces. ◇◆ sava-scratch.spaces.
2007-04-22 19:54
aipb2007
Rank: 8Rank: 8
来 自:CQU
等 级:贵宾
威 望:40
帖 子:2879
专家分:7
注 册:2007-3-18
收藏
得分:0 

懂你的意思了,原来有3个参数

我再琢磨下!

many thanks!


Fight  to win  or  die...
2007-04-22 21:55
快速回复:“游乐园”进,关于map.
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.020678 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved