gpt4 book ai didi

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

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

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

例子:

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] 中搜索一个相同的词?我怎样才能正确地做到这一点?

最佳答案

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

“我以前从未使用过 map ,所以我不太确定如何实现它...”

#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

关于c++ - 如何使我的程序接受多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19388488/

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