簡體   English   中英

C++ 字符串比較在字數統計算法的向量迭代中不起作用

[英]C++ String comparison not working in vector iteration for word counting algorithm

我是 c++ 編程的新手,目前正在嘗試創建一個程序來計算字符串 from.txt 文件中每個單詞的數量。

我現在的問題是,當我使用 vector 來存儲每個單詞並通過比較計算相同的單詞時,它有時會跳過一些單詞。

    for(int i = 0;i<words.size();i++) {  //Using nested for loops to counts the words
        finalWords.push_back(words[i]);//Words that are unique will be counted 
        int counts = 1;
        for(int j = i + 1; j<words.size();j++) {
            if(words[i] == words[j]) {
                counts++;
                words.erase(words.begin() + j); //Removing the words that is not unique
             }
             continue;
         }
         wordCount.push_back(counts);
     }

在我的完整代碼中,words 是一個用相似詞填充的字符串向量,finalWords 是一個空字符串向量,wordCount 是 int 向量,用於存儲 finalWords 向量中的單詞數量。 我認為問題是未打印的字符,如換行符,但是當我檢查輸入時,它不是比較運算符無法正確比較的接近換行符的字符串。 我錯過了什么嗎? 如果有,我需要做什么來修復它?

先感謝您!

當您擦除索引j處的元素時,下一個元素將位於索引j處,而不是索引j+1處。

循環應該 go 有點像這樣:

for(int j = i + 1; j<words.size(); ) {   // no increment here
     if (erasse_it) {
         words.erase(words.begin() + j);
         // no increment here
     } else { 
         ++j;    // increment here
     }
}

但是,正如其他人提到的那樣,您的代碼不必要地復雜化且效率低下。

您可以使用std::unordered_map來計算頻率:

  std::unordered_map<std::string, unsigned> freq;
  for (const auto& word : words) {
       ++freq[word];
  }

  for (const auto& f : freq) {
       std::cout << f.first << " appears " << f.second << " times";
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM