C ++ map用于跟踪到达地图结尾的时间

时间:2010-06-18 15:26:03

标签: c++ stl map

目前我有一张打印出以下内容的地图

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

如何检查内部地图内的地图结尾?   任何帮助将不胜感激谢谢

7 个答案:

答案 0 :(得分:9)

更改输出行以首先打印逗号,并且仅当它不是第一个元素时才会打印:

if (inner != outer->second.begin())
    std::cout << ",";
std::cout << inner->first << "," << inner->second;

答案 1 :(得分:7)

我将其更改为使用std::copy,我将其与infix_ostream_iterator一起使用。

编辑:我还记录了你正在做的事情看起来非常像std::multimap。如果你不想使用多图,它看起来仍然很简单:

std::ostream &operator<<(std::ostream &os, std::vector<int> const &v) { 
    std::copy(v.begin(), v.end(),
              infix_ostream_iterator<int>(os, ","));
    return os;
}

std::map<std::string, std::vector<int> > mapper;

std::copy(mapper.begin(), mapper.end(), 
          std::ostream_iterator<std::vector<int> >(std::cout, "\n");

答案 2 :(得分:2)

  for(inner = m->second.begin(); inner != m->second.end(); inner++){ 
      cout<<inner->first<<","<<inner->second;
      if (next(inner) != m->second.end()){
          cout<<",";
      }
  } 

修改:有人指出map::iterator不支持添加,而且合适的替代品是非标准next功能。我已经更新了上面的代码,这是我自己的next版本。

template<typename T>
T next(T incrementable)
{
    return ++incrementable;
}

答案 3 :(得分:1)

您可以将结果存储在字符串中,例如并修剪for。之后的最后一个字符。

答案 4 :(得分:1)

您需要修改内部循环,以便在开始时为除第一次迭代之外的每次迭代打印逗号分隔符,如:

// inside the loop
cout << ( inner == outer->second.begin() ? "" : "," ) << inner->first << "," << inner->second;

答案 5 :(得分:0)

您已经指定了如何在技术上解决问题“找到循环结束”,但您尝试解决的格式可以通过其他方式进行管理。

展开内循环,然后移动分隔符。

for(m = mapper.begin(); m != mapper.end(); m++){
    cout<<m->first<<": ";

  if( inner = m->second.begin() != m->second.end() ) {
    cout<<inner->first<<","<<inner->second;
    ++inner
    for(; inner != m->second.end(); ++inner){
      cout<<","<<inner->first<<","<<inner->second;
    }
  }
}

这意味着您不必在循环的每次迭代中进行if测试

答案 6 :(得分:0)

将内循环更改为:

if(outter->second.size()) {
    inner = outter->second.begin();
    while(true) {
        cout<<inner->first<<","<<inner->second;
        if(++inner != outer->second.end()) {
            cout<<",";
        } else {
            break;
        }
    }
}