将字符串映射到无符号 int 到无符号 int 的映射

Mapping string to map of unsigned int to unsigned int

本文关键字:int 无符号 映射 字符串      更新时间:2023-10-16

我试图将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++;
 }
      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;
}