第十七章 17 1 2節練習

2021-06-26 04:00:20 字數 1400 閱讀 6469

練習17.4

編寫並測試你自己版本的findbook函式。

解答:實現參考書中實現。

練習17.5

重寫findbook,令其返回乙個pair,包含乙個索引和乙個迭代器pair。

解答:

typedef pair::size_type, pair::const_iterator, vector::const_iterator>> matches;

pair>

findbook(const vector> &files, const string &book)

return ret; // empty if no matches found

}

練習17.6

重寫findbook,不使用tuple或pair。

解答:

template class matches_result

vector::size_type index;

vector::const_iterator first, second;

};matches_resultfindbook(const vector> &files, const string &book)

return ret; // empty if no matches found

}

這裡構造了乙個儲存資料的類來進行記錄。

當需要對結果進行處理的時候,這個類可以包含在處理類中。

練習17.7

解釋你更傾向於哪個版本的findbook,為什麼。

解答:我會更偏向於使用tuple的版本。

易與理解,且**實現比較簡單。

練習17.8

在本節最後一段**中,如果我們將sales_data()作為第三個引數傳遞給accumulate,會發生什麼?

解答:先看一下accumulate的等價實現

template

t accumulate (inputiterator first, inputiterator last, t init)

return init;

}

sales_data的+=操作符

sales_data& sales_data::operator+=(const sales_data &rhs)

sales_data的《操作符

ostream &operator<<(ostream &os, const sales_data &item)

從上面可以看出,替換為sales_data(), 序執行上是沒有太大的影響,只不過會在輸出的時候,本來應該顯示bookno的地方是空的。

第十七章 17 1 1節練習

練習17.1 定義乙個儲存三個int值的tuple,並將其成員分別初始化為10 20和30。解答 include include int main 練習17.2 定義乙個tuple,儲存乙個string 乙個vector和乙個pair。解答 include include include inclu...

第十七章 17 3 1節練習

練習17.14 編寫幾個正規表示式,分別觸發不同錯誤。執行你的程式,觀察編譯器對每個錯誤的輸出。解答 這個就不一一枚舉出來了。如果正規表示式寫錯,在執行時程式會在編譯表示式的時候直接崩潰。練習17.15 編寫程式,使用模式查詢違反 i在e之前,除非在c之後 規則的單詞。你的程式應該提示使用者輸入乙個...

第十七章 17 3 4節練習

練習17.24 編寫你自己版本的重排 號碼格式的程式。解答 這個參考書中實現。練習17.25 重寫你的 號碼程式,使之只輸出每個人的第乙個 號碼。解答 include include include include using namespace std using namespace std re...