以特定顺序输出地图

时间:2014-01-26 02:41:10

标签: c++ sorting maps output

希望我能够准确地解释发生了什么,但基本上我在程序读入的文档上有一个单词地图及其对应的行号。我可以用字和行号输出地图和所有内容,但我对如何改变输出方式感到困惑。所以这是代码:

这里是主要的:

#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

我在代码中出现了什么问题,或者我是否需要添加排序函数来对其进行排序?我老实说迷路了,不知道从哪里开始,只能输出一次单词,然后输出它出现的行号。如果有人能提供帮助那就太棒了,如果需要更多信息,我很乐意将其添加到问题中!谢谢!

1 个答案:

答案 0 :(得分:1)

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

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