谢谢各位大哥:怎么样遍历Map

xi_yao 2003-10-16 09:15:52
我Map申明是map(string,int)
...全文
540 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
hdqqq 2003-10-29
  • 打赏
  • 举报
回复
是不是改成
map<string, int> m;
map<strint, int>::iterator it = m.begin();
for( ;it != m.end();it++)
{
//...
}

好一点,
map<string, int> m;
map<strint, int>::iterator it = m.begin();
while (it++ != m.end())
{
//...
}
中,不敢确定it++的调用发生在循环中的语句前还是后
xkak2 2003-10-28
  • 打赏
  • 举报
回复
STL之所以是标准库,就在于它奉行一套标准化的理念,例如:容器的iterator可以遍历容器。STL,以及按照STL扩展的库,容器不一定支持[],但是一定支持前向iterator。
wangyangcheng 2003-10-28
  • 打赏
  • 举报
回复
up!@
wangyangcheng 2003-10-27
  • 打赏
  • 举报
回复
我想知道遍歷map可否像vector一樣用subscript來實現?
如﹕
#pragma warning (disable:4786)
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string,int> t_map;
t_map["camel"]=7;
t_map["both"]=10;
cout<<t_map[0]->first<<"\n"<<t_map[0]->second<<endl;

return 0;
}


謝謝﹗
JohnFractal 2003-10-17
  • 打赏
  • 举报
回复
这样可以吧:

map<string,int> aMap;

struct ShowKey{
void operator()(map<string,int>::value_type& val){
cout << val.first << endl;
}
}aFun;

for_each( aMap.begin(), aMap.end(), aFun );
TopCoderONE 2003-10-17
  • 打赏
  • 举报
回复
你的i如果是一个指针的话,用(*i)->first
njSeeWhy 2003-10-16
  • 打赏
  • 举报
回复
就按照一般的容器类的遍历方式就可以了,比如楼上的做法就是一种呀。我想likangnian0128(likangnian0128)可能没看明白,楼主问的应该是STL库中的map容器类吧,不是一般数据结构里所讲的map,呵呵。
Wolf0403 2003-10-16
  • 打赏
  • 举报
回复
std::map is sorted with the key provided as the first template class paramater, and can be iterated with map::iterator.
map<string, int> m;
map<strint, int>::iterator it = m.begin();
while (it++ != m.end())
{
//...
}
likangnian0128 2003-10-16
  • 打赏
  • 举报
回复
…………你声明成什么样都没有关系,反正我没有时间给你写源码。

map周游可以用:
1。深度优先周游
从任何一个节点a1开始,设a1为已经访问。
访问a1的第一个未访问过的相邻节点a2,设置a2为已经访问
再访问a2的第一个未访问过的相邻节点a3,设置a3为已经访问……

直到an已经没有未访问的相邻节点,此时退回a(n-1),访问a(n-1)的第一个未访问的相邻节点……

一直重复以上动作,当你回到a1,并且a1已经没有未访问过的相邻节点,那就是周游完成。

提醒你:用栈来保存a1、a2……的访问序列



2。广度优先周游
要使用队列:

从任何一个节点a1开始,设a1为已经访问。
访问a1的所有未访问过的节点,将它们全设为已经访问,并将它们放入队列
出队一个节点a2,访问a2所有未访问过的节点,将它们全设为已经访问,并将它们放入队列……
重复出队、访问、入队的过程,直到队列为空,就是周游完成。

Wolf0403 2003-10-16
  • 打赏
  • 举报
回复
i->first 是什么东西?
xi_yao 2003-10-16
  • 打赏
  • 举报
回复
是啊是啊,不过还有个问题,我用的上面那个大哥的办法现在
i=Intlist.begin();
while (i++!=Intlist.end())
{
if ((*i).second!=-9999)
{
cout<<i->first<<endl;
}
}
现在的问题是执行到cout<<i->first<<endl;
时总是报错,具体错误为“程序产生一个访问违例(段异常)”怎么回事?

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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