我正在尝试将 cin 中的每个单词映射到该单词出现的行号以及它出现的行以及它在该行出现的次数。
我不确定我的循环是否有效。我想我对 map 有所了解,但我不能 100% 确定这是否可行,而且我无法打印它进行测试,因为我还没有弄清楚应该如何打印它。我的问题是,我的 map 看起来还好吗?
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 */
要打印它,只需循环遍历您的 map :
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;
}
关于c++ - 将字符串映射到 unsigned int 到 unsigned int 的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29614494/