Accelerated C++ 第3章 課題残り

3-3

vectorを2個使用して、単語そのものと、出現回数用の2個vectorを使う。でも連想配列(map)を使うのが素直。まだ出てきてないですが。

#include <iostream>
#include <string>
#include <vector>

using std::cin;     using std::cout;    using std::endl;
using std::vector;  using std::string;

int main()
{
    vector<string>  vwords;
    vector<int>     vcounts;
    string word;
    
    while (cin >> word) {
        bool found = false;
        for (int i = 0; i < vwords.size(); ++i) {
            if (vwords[i] == word) {
                 ++vcounts[i];
                found = true;
                break;
            }
        }
        if (!found) {
            vwords.push_back(word);
            vcounts.push_back(1);
        }
    }

    for (int i = 0; i < vwords.size(); ++i) {
        cout << vwords[i] << ": " << vcounts[i] << endl;
    }
    return 0;
}

登録済みかどうかで、さらっと == で比較しているけど、オブジェクト同士の比較なので、本当は同一判定なのか、同値判定なのかが大切。
実際にやってみると、==は同値判定でした。

#include <iostream>
#include <string>

using std::cout;        using std::endl;
using std::string;

int main()
{
    string  s1 = "abc";
    string  s2 = "abc";
    string  s3 = "a";

    cout    << "s1 == s2\t"
            << ((s1 == s2)? "true": "false") << endl;
    cout    << "s1 == \"abc\"\t"
            << ((s1 == "abc")? "true": "false") << endl;
    cout    << "s1 == s3 + \"bc\"\t"
            << ((s1 == s3 + "bc")? "true": "false") << endl;
    cout    << "s1 == string(\"ab\") + \"c\"\t"
            << ((s1 == string("ab") + "c")? "true": "false") << endl;
    return 0;
}
3-4

最初に1単語入力して・・というのが素直かとも思うけど、string::size_typeが符号なしということなので、最小値の初期値を -1 で初期化してみた。

#include <iostream>
#include <string>

using std::cin;     using std::cout;    using std::endl;     using std::string;

int main()
{

    string::size_type   min = -1;
    string::size_type   max = 0;
    
    string word;
    while (cin >> word) {
        if (word.size() < min) {
            min = word.size();
        }
        if (word.size() > max) {
            max = word.size();
        }
    }
    cout << "min = " << min << endl;
    cout << "max = " << max << endl;
    
    return 0;
}
3-5

さすがに面倒になってきたので省略。
宿題の数が最初からわかっている・・というのは1人分の入力でEOFとしたあと、cinから入力できなくなるためと思われ。$4.1.3のclear()を使えば回避可能。