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

iam*_*rus 0 c++ string vector

我正在尝试创建一个将文件读入字符串向量的字典,并计算每个唯一字出现的次数.这是我到目前为止所拥有的:

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);

            }
    }
Run Code Online (Sandbox Code Playgroud)

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

Nar*_*oot 5

这是非常低效的.你应该用

 std::map<string, int> 
Run Code Online (Sandbox Code Playgroud)

代替.它既简单又有效.

循环遍历文件.当你看到一个单词时,看看它是否在地图中.如果不是,请添加一个带有计数的新单词1.如果是,则递增计数.