【问题标题】:Mapping string to map of unsigned int to unsigned int将字符串映射到 unsigned int 到 unsigned int 的映射
【发布时间】:2015-04-13 20:29:24
【问题描述】:

我正在尝试将每个单词从 cin 映射到该单词出现的行号,以及它出现在该行上的次数。

我不确定我的循环是否有效。我想我对地图有所了解,但我不能 100% 确定这是否可行,我无法打印出来进行测试,因为我还没有弄清楚应该如何打印它。我的问题是,我的地图看起来还好吗?

int main ( int argc, char *argv[] )
{
  map<string, map<unsigned int, unsigned int> > table;

  unsigned int linenum = 1;
  string line;

  while ( getline(cin, line) != cin.eof()){
    istringstream iss(line);
    string word;
    while(iss  >> word){
      ++table[word][linenum];
    }
    linenum++;
 }

【问题讨论】:

    标签: c++ dictionary stl stream


    【解决方案1】:
          while ( getline(cin, line) != cin.eof() ){
                                    /*~~~~~~~~~~~~ Don't use this, 
                                                   the comparison is incorrect */
    

    要打印它,只需遍历您的地图:

    for(const auto& x:table)
    { 
        std::cout << x.first << ' ';
        for(const auto& y:x.second)
        {
         std::cout << y.first << ":" << y.second << ' ';
        }
        std::cout << std::endl;
    }
    

    here

    对于 C++98 使用:

        for(mIt x = table.begin();
            x != table.end();
            ++x )
    { 
        std::cout << x->first << ' ' ;
        for( It y = x->second.begin();
            y != x->second.end();
            ++y )
        {
         std::cout << y->first << ":" << y->second << ' ';
        }
    
        std::cout << std::endl;
    }
    

    【讨论】:

    • 不幸的是我只能使用 c98 @P0W
    • @etorr96 它们的返回类型不同,请参阅相应的参考资料
    猜你喜欢
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2015-11-15
    • 1970-01-01
    相关资源
    最近更新 更多