请教map 的删除

HNLGDXYJS 2011-08-17 04:56:29
大家好:

1、map<int, list<f_msg> > mapf;
2、map<int, dir> mapd;

对于第一种, 怎么清空 map 里的 list, 在清空 map.

对于第二种, 是不是直接 mapd.clear() 就搞定了。

请赐教, 谢谢。
...全文
195 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
HNLGDXYJS 2011-08-17
  • 打赏
  • 举报
回复
谢谢大家。
莫欺少年穷 2011-08-17
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 notonlyforshe 的回复:]
public static void main(String[] args) {
Map<Integer,List<String>> mapList = new HashMap<Integer, List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("first");
List<String> li……
[/Quote]

控制台只会打印出来分割线,其他的都没有执行,说明清空了一切,list存在于map,自然无法获取...
莫欺少年穷 2011-08-17
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 hnlgdxyjs 的回复:]
引用 2 楼 notonlyforshe 的回复:
clear()方法是直接清空的,包括key和value!!!也就是第二种的全部清空了!!!第一种,不需要清空list,直接clear一样清空map!!


想起来了, 你这种办法是不是只清空了map, map里的 list 也会被清空吧? 没有自己再申请内存。
[/Quote]

list就存在于map里面,清空map自然消失了list...不再申请内存。
luciferisnotsatan 2011-08-17
  • 打赏
  • 举报
回复
1 f_msg是啥?不是指针的,并且自己有析构函数,可以直接clear。list有析构函数,会自己清理。不然就迭代器遍历map,把second一一清空。

2 dir是什么?不是指针的,并且自己有析构函数,可以直接clear
莫欺少年穷 2011-08-17
  • 打赏
  • 举报
回复
public static void main(String[] args) {
Map<Integer,List<String>> mapList = new HashMap<Integer, List<String>>();
List<String> list1 = new ArrayList<String>();
list1.add("first");
List<String> list2 = new ArrayList<String>();
list2.add("second");
mapList.put(1, list1);
mapList.put(2, list2);
mapList.clear();
for (Integer key : mapList.keySet()) {
for (String string : mapList.get(key)) {
System.out.println(string);
}
}
System.out.println("------------------------------------");
Map<Integer,String> mapString = new HashMap<Integer, String>();
mapString.put(1, "first");
mapString.put(2, "second");
mapString.clear();
for (Integer key : mapString.keySet()) {
System.out.println(mapList.get(key));
}
}
HNLGDXYJS 2011-08-17
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 notonlyforshe 的回复:]
clear()方法是直接清空的,包括key和value!!!也就是第二种的全部清空了!!!第一种,不需要清空list,直接clear一样清空map!!
[/Quote]

想起来了, 你这种办法是不是只清空了map, map里的 list 也会被清空吧? 没有自己再申请内存。
quwei197874 2011-08-17
  • 打赏
  • 举报
回复
循环删除呗
HNLGDXYJS 2011-08-17
  • 打赏
  • 举报
回复
非常感谢, 结贴给分。按 1,3 楼的办法。
war10811 2011-08-17
  • 打赏
  • 举报
回复
f_msg
dir
要看这2个是啥,
没动态内存分配的话
2种都直接clear()就行了
否则要先DELETE掉指针指向的内存
  • 打赏
  • 举报
回复
1 同样 mapf.clear(); 就可以了。。
大海啊全是水 2011-08-17
  • 打赏
  • 举报
回复
map<int, list<f_msg> >::iterator it;
for(it = mapf.begin(); it != mapf.end(); it++){
//.....
it->second.clear();
}
mapf.clear();
莫欺少年穷 2011-08-17
  • 打赏
  • 举报
回复
clear()方法是直接清空的,包括key和value!!!也就是第二种的全部清空了!!!第一种,不需要清空list,直接clear一样清空map!!
莫欺少年穷 2011-08-17
  • 打赏
  • 举报
回复
此贴必火,占楼先!

65,199

社区成员

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

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