以特定顺序输出地图

Outputting a map in a specific order

本文关键字:输出地 地图 输出 定顺序      更新时间:2023-10-16

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

这是主要的:

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

}

因此,最后一个功能是执行地图的输出,并且输出如下:

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