计算字符串向量中单词的出现次数

Counting occurrences of words in a string vector

本文关键字:单词 字符串 向量 计算      更新时间:2023-10-16

我正在尝试创建一个字典,将文件读取为字符串向量,并计算每个唯一单词出现的次数。以下是目前为止的内容:

int main()
{
    ifstream input1;
    input1.open("Base_text.txt");
    vector<string> base_file;
    vector<int> base_count;

    if (input1.fail())
    {
        cout<<"Input file 1 opening failed."<<endl;
        exit(1);
    }
    make_dictionary(input1, base_file, base_count);

}
void make_dictionary(istream& file, vector<string>& words, vector<int>& count)
{

    string word;
    int i=0;
    while (file>>word)
    {
        words.push_back(word);
        cout<<words[i];
        i++;
    }

    for (i=0; i<words.size(); i++)
    {
        if ((words[i+1]!=words[i]))
            {
                count.push_back(i);
            }
    }

问题1:如何让向量包含空格并识别单个单词?问题2:对于如何继续第二部分(for循环)有什么想法吗?

这是相当低效的。你应该使用

 std::map<string, int> 

。这既容易又有效。

遍历文件。当你看到一个单词时,看看它是否在地图上。如果不是,则添加一个计数为1的新单词。