如何使我的程序接受多个单词

How to make it so that my program accepts multiple words

本文关键字:单词 何使 我的 程序      更新时间:2023-10-16

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

例:

teddy bears are cute
so are you

因此,它将泰迪熊存储为第 1 行,熊存储为第 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.
}

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

这不是您问题的解决方案,我正在回答您的评论

"我以前从未使用过地图,所以我不完全确定如何实现它......"

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

Input.txt的内容:

teddy bears are cute
so are you

输出:

are:1 2
bears:1
cute:1
so:2
teddy:1
you:2