gpt4 book ai didi

c++ - 按特定顺序输出 map

转载 作者:行者123 更新时间:2023-11-28 07:08:44 24 4
gpt4 key购买 nike

希望我能准确解释发生了什么,但基本上我在程序读取的文档中有一个单词映射及其对应的行号。我可以输出 map 和所有带有单词及其行号的内容,但我对如何更改它们的输出方式感到困惑。所以这是代码:

这里是主要的:

#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
#include <fstream>
#include "dictionary.h"
#include "document.h"

using namespace std;

void sentancetoword(string sentance, set<string> words, int lineNum)
{
dictionary d;
document doc;
bool wordCheck;
string word;
stringstream ss(sentance);

while (ss >> word)
{
wordCheck = d.findWord(word, words);
if(!wordCheck)
{
doc.missingMap(word, lineNum);
}
}
doc.displayMap();

}

string letterCheck(string sentance)
{
for(unsigned i = 0; i < sentance.length(); i++)
{
if (!isalpha(sentance[i]))
{
sentance[i] = ' ';
}
}
return sentance;
}

int main(int argc, char* argv[])
{
dictionary dic;
document doc;
set<string> words;
set<string>::iterator it;
string doc_word;
int lineNum = 1;
ifstream in;
in.open(argv[1]);
string word;

while (in >> word)
{
transform(word.begin(), word.end(), word.begin(), ::tolower);
words.insert(word);
}

in.close();

//dic.makeSet(words);

ifstream in2;
in2.open(argv[2]);
while (getline(in2, doc_word))
{
transform(doc_word.begin(), doc_word.end(), doc_word.begin(), ::tolower);
doc_word = letterCheck(doc_word);
sentancetoword(doc_word, words, lineNum);
lineNum++;

}

in2.close();

system("pause");
return 0;

}


#include "document.h"


document::document(void){}
document::~document(void){}

void document::missingMap(string word, int lineNum)
{
misspelled[word].push_back(lineNum);
}
void document::displayMap()
{
for (map<string, vector<int>>::iterator i = misspelled.begin(); i != misspelled.end(); i++)
{
cout << i->first << ": ";
for (vector<int>::iterator j = i->second.begin(); j != i->second.end(); j++)
{
cout << *j << endl;
}
}



}

所以最后一个函数是做 map 的输出,输出如下:

debugging: 1
process: 2
removing: 2
programming: 3
process: 4
putting: 4

但我需要它像这样输出:

debugging: 1
process: 2 4
programming: 3
putting: 4
removing: 2

是我在代码中做错了什么,还是我需要添加一个排序函数来按单词排序?老实说,我迷路了,不知道从这里到哪里才能让它只输出一次单词,然后输出它出现的行号。如果有人可以提供帮助,那就太好了,如果需要更多信息,我很乐意将其添加到问题中!谢谢!

最佳答案

你的输出没有意义,但我认为你会想要这样做:

cout << i->first << ": ";
for (vector<int>::iterator j = i->second.begin(); j != i->second.end(); j++)
{
cout << *j << " ";
}
cout << "\n"; //endl is okay, but I prefer only for I really do need to flush the stream

关于c++ - 按特定顺序输出 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21358981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com