阿摩線上測驗 登入

申論題資訊

試卷:104年 - 104年第二次程式設計#41545
科目:程式設計
年份:104年
排序:0

申論題內容

二、請實做一 Java 方法 m(String[ ] s)或 C++函式 m(int size, string s[ ]),可以對傳入的陣
列中的字串進行分析。主要任務是識別相異字串、計算共有多少相異字串、以及統
計每一相異字串的出現次數、最後並將統計結果印出。為使程式精簡,實做時請儘
量叫用標準 Java/C++程式庫的既有套件程式而避免自行重做。以下是使用範例:假
設傳入的陣列 s 內容為 {"80","90","10","70","90","90","10"},則輸出的結果應如下
文所示:
There are 4 distinct words:80,90,10,70.
80 occurs 1 time .
90 occurs 3 times .
10 ouucrs 2 times .
70 occurs 1 time .
(20 分)





詳解 (共 1 筆)

詳解 提供者:hchungw
#include <iostream>
#include <map>
#include <string>
using namespace std;
void m(int size, string s[]) {
    map<string, int> wordCounts;
    for (int i = 0; i < size; ++i) {
        wordCounts[s[i]]++;
    }
    cout << "There are " << wordCounts.size() << " distinct words:";
    for (auto it = wordCounts.begin(); it != wordCounts.end(); ++it) {
        if (it != wordCounts.begin()) {
            cout << ",";
        }
        cout << it->first;
    }
    cout << "." << endl;
    
    for (const auto& pair : wordCounts) {
        cout << pair.first << " occurs " << pair.second << (pair.second > 1 ? " times" : " time") << " ." << endl;
    }
}
int main() {
    string s[] = {"80", "90", "10", "70", "90", "90", "10"};
    int size = sizeof(s) / sizeof(s[0]);
    m(size, s);
    return 0;
}
這兩個程式都使用了相應語言的標準程式庫中的容器來存儲和計數每個獨特字串的出現次數。Java版本使用了HashMap來實現這一功能,而C++版本則使用了std::map。兩者都能有效地完成任務,並按要求輸出結果。