0

我正在制作一个列表向量的程序。它正在跟踪一个单词,以及该单词所在的行号。

例子:

teddy bears are cute
so are you

因此,它将 teddy 存储为第 1 行。 bears 存储为第 1 行。我遇到的唯一问题是重复单词时。它将存储为第 1 行,但我希望程序也存储为第 2 行。我不确定我该怎么做。这是我到目前为止的代码

class index_table
{

public:
    index_table() { table.resize(128);}
    vector <int> &find1(string &);

private:
    class entry
    {
        public:
        string word;
        vector <int> line;
    };

    vector< list <entry> > table;



};

void index_table :: insert( string & key, int value)
{
entry obj;
int c = key[0]; //vector for the table.
obj.word = key; //Storing word
obj.line.push_back(value); //Storing what line it was found on

table[c].push_back(obj); //Stores the word and line number.

}

我怎样才能使我的程序可以在不同的数字行上存储多个单词?我将不得不在我的 table[c] 中搜索一个单词是否相同?我怎样才能正确地做到这一点?

4

1 回答 1

2

This is not the solution for your problem instead, I'm answering your comment

"I've never used a map before so I'm not entirely sure how to implement it..."

#include<iostream>
#include<fstream>
#include<sstream>
#include<map>
#include<set>

int main()
{
    std::map< std::string, std::set<int> > word_count;

    std::ifstream input_file("input.txt");
    std::string single_line, single_word;
    int line_number = 0;

    while(std::getline(input_file, single_line))
    {
        ++line_number;
        std::stringstream word_reader(single_line);

        while(word_reader >> single_word)
        {
            word_count[single_word].insert(line_number);
        }
    }

    input_file.close();

    for(auto word:word_count)
    {
        std::cout << word.first << ":";

        for(auto line:word.second)
        {
            std::cout << line << " ";
        }

        std::cout << std::endl;
    }
}

The contents of Input.txt :

teddy bears are cute
so are you

Outputs :

are:1 2
bears:1
cute:1
so:2
teddy:1
you:2
于 2013-10-15T18:58:28.527 回答