没有地图的向量的字计数器

Word counter of a vector without map

如何计算单词向量中每个单词出现的次数?

我能够得到向量中的所有单词,但现在我无法计算每个单词出现了多少次。

vector <Phrase> mots; // it's already filled with words of type Phrase (string)
int count = 1;
Phrase *word = &mots[0];
for (unsigned i = 1; i < mots.size(); i ++ ){
        if ( word != &mots[i] ){
             cout << *word <<" occured " << count << " times " <<endl;
             count = 0;
             word = &mots[i]; // I'm pretty sure I'm doing this line wrong 
        }
      count ++;
 }
cout << word <<" occured " << count << " times " <<endl;

谢谢

这里是我填充向量的地方: 这些是文本的迭代器

for( Histoire * histoire : * histoires ) {
      for( Phrase p : * histoire ) {
            for ( Phrase w : p ){
                        mots.push_back(w);
            }
      }
}

你可以用 vector<pair<string, int>> 模拟 map<string, int>,你最终会得到这样的结果:

std::vector<std::string> mots = {"a", "b", "c", "a", "c"}; // <- this is just for the example
vector<pair<string, int>> counts;
std::for_each(mots.begin(), mots.end(), [&](auto& el){ // <- for each word
    auto index = std::find_if(counts.begin(), counts.end(), [&](auto & pair){
        return pair.first == el;
    }); // <- check if you already have registered in counts a pair with that string
    if(index == counts.end()) // <- if no, register with count 1
        counts.emplace_back(el, 1);
    else // otherwise increment the counter
        (*index).second++;
});
for(auto& el : counts)
    cout << "Word " << el.first << " occurs "<< el.second << " times";

输出:

Word a occurs 2 times
Word b occurs 1 times
Word c occurs 2 times