C++当到达地图末尾时进行地图跟踪
目前我有一张地图,可以打印出以下内容
map<string, map<int,int> > mapper;
map<int,int>::iterator inner;
map<string, map<int,int> >::iterator outer;
for(outer = mapper.begin(); outer != mapper.end(); outer++){
cout<<outer->first<<": ";
for(inner = outer->second.begin(); inner != outer->second.end(); inner++){
cout<<inner->first<<","<<inner->second<<",";
}
}
截至目前,这会打印出以下内容
stringone: 1,2,3,4,6,7,8,
stringtwo: 3,5,6,7,
stringthree: 2,3,4,5,
我希望它打印出的是
stringone: 1,2,3,4,6,7,8
stringtwo: 3,5,6,7
stringthree: 2,3,4,5
如何检查内部地图内地图的末尾? 任何帮助将不胜感激谢谢
Currently I have a map that prints out the following
map<string, map<int,int> > mapper;
map<int,int>::iterator inner;
map<string, map<int,int> >::iterator outer;
for(outer = mapper.begin(); outer != mapper.end(); outer++){
cout<<outer->first<<": ";
for(inner = outer->second.begin(); inner != outer->second.end(); inner++){
cout<<inner->first<<","<<inner->second<<",";
}
}
As of now this prints out the following
stringone: 1,2,3,4,6,7,8,
stringtwo: 3,5,6,7,
stringthree: 2,3,4,5,
What i want it to print out is
stringone: 1,2,3,4,6,7,8
stringtwo: 3,5,6,7
stringthree: 2,3,4,5
how can i check for the end of the map inside my inner map?
Any help would be appreciated Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
更改输出行以首先打印逗号,并且仅当它不是第一个元素时:
Change your output line to print the comma first and only if it is not the first element:
我将其更改为使用
std::copy
,我将其与infix_ostream_iterator
。编辑:我还要记录一下,您所做的事情看起来非常像
std::multimap
。如果您不想使用多重贴图,看起来仍然是更简单的方法,如下所示:I'd change it to use
std::copy
, which I'd use along with aninfix_ostream_iterator
.Edit: I'd also note for the record that what you're doing looks an awful lot like an
std::multimap
. If you don't want to use a multimap, it still looks like a lot simpler way to go would be something like:编辑:有人指出,
map::iterator
不支持加法,合适的替代品是非标准next
函数。我更新了上面的代码,这是我自己的next
版本。Edit: It has been pointed out that
map::iterator
doesn't support addition, and that a suitable substitute is a nonstandardnext
function. I've updated the above code, and here's my own version ofnext
.例如,您可以将结果存储在字符串中,并修剪 for 之后的最后一个字符。
You could store the result in a string for example and trim the last character after the for.
您需要修改内部循环,以便它在除第一次之外的每次迭代的开头打印逗号分隔符,如下所示:
You need to modify your inner loop so that it prints the comma separator at the start for each iteration other than the first, something like:
将您的内循环更改为:
Change your inner loop to this:
您已指定如何从技术上解决问题“找到循环的末尾”,但您尝试解决的格式可以通过其他方式进行管理。
展开内环,然后移动分隔符。
这意味着您不必在循环的每次迭代中进行 in if 测试
You have specified how you want to solve your problem technically 'finding the end of the loop' but the formatting you are trying to resolve can be managed in other ways.
Unroll the inner loop, and move the seperator.
This means you don't have to do a in if test in each iteration of the loop