STL map的问题

darkarthur 2007-12-06 04:31:39
#include <iostream>
#include <map>
#include <string>
using namespace std;
void main ()
{
string input;
typedef map<string, int> StrIntMap;
StrIntMap ma;
long i = 0;
while (cin>>input && input != "fuck")
{
ma[input] = i;
}

map<string, int>::iterator pos1;
map<string, int>::iterator pos2;

for (pos1 = ma.begin(); pos1 != ma.end(); pos1++)
{
for (pos2 = ma.begin(); pos2 != ma.end(); pos2++)
{
if (pos1->first == pos2->first) ++i;
}
ma[pos1->first] = i;
i = 0;
}

for (pos1 = ma.begin(); pos1 != ma.end(); pos1++)
{
cout<<pos1->first<<" "<<pos1->second<<"\n";
}
}

我的代码是这样的
输出的时候i的值永远都是1
调试的时候pos1->first的值不能看到
初学习STL 问题很多 = =
...全文
73 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yydrewdrew 2007-12-06
  • 打赏
  • 举报
回复
题外:pos1++最好写成++pos1
yydrewdrew 2007-12-06
  • 打赏
  • 举报
回复
题外:pos1++最好写成++pos1
xalangying 2007-12-06
  • 打赏
  • 举报
回复
修正,楼上的mulset应为 multimap
xalangying 2007-12-06
  • 打赏
  • 举报
回复
因为map对key相等的值只能保留一个,你应该把你程序的map改为mulset或改成以下这样就能实现你想要的功能
#include <iostream>
#include <map>
#include <string>
using namespace std;
void main ()
{
string input;
typedef map<string, int> StrIntMap;
StrIntMap ma;
long i = 0;
while (cin>>input && input != "fuck")
{
ma[input]++;
}
map<string, int>::iterator pos1;
for (pos1 = ma.begin(); pos1 != ma.end(); pos1++)
{
cout<<pos1->first<<" "<<pos1->second<<"\n";
}
}
darkarthur 2007-12-06
  • 打赏
  • 举报
回复
是我把map的概念和multimap的概念混淆了
最后我实现的程序是这样的 谢谢大家的说
#include <iostream>
#include <map>
#include <string>
using namespace std;
void main ()
{
string input;
map<string, int> ma;
while (cin>>input && input != "fuck")
{
ma[input]++;
}
map<string, int>::reverse_iterator it=ma.rbegin();
cout<<(*it).first<<" "<<(*it).second<<endl;
}

64,687

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧