etorr96
etorr96

Reputation: 79

Mapping string to map of unsigned int to unsigned int

I am attempting to map every word from cin to the line number that word occurs on to the line it occurs on and the number of times it occurs on the line.

I'm not sure if my loop will work. I think I have an understanding on maps but I'm not 100% sure if this will work and I cant print it to test because I haven't figured out how I should print it. My question is, does my map look okay?

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++;
 }

Upvotes: 0

Views: 1550

Answers (1)

P0W
P0W

Reputation: 47794

      while ( getline(cin, line) != cin.eof() ){
                                /*~~~~~~~~~~~~ Don't use this, 
                                               the comparison is incorrect */

To print it simply loop over your map of maps:

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;
}

See here

For C++98 use:

    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;
}

Upvotes: 1

Related Questions