2021年2月17日 星期三

Q1--Library Database 解題筆記

題目簡介

請根據使用者輸入的命令,模擬圖書資料庫,並做出相對應的操作。

指令如下:

(1) Insert: Insert "title" "author" "edition"

(2) Delete Edition: Delete Edition "title" "author" "edition"

(3) Delete Book: Delete Book "title" "author"

(4) Find Book: Find Book "title" "author"

(5) Find Author: Find Author "author"

(6) Sort by Title: Sort by "title"

(7) Sort by Author: Sort by "author"


解題筆記

一、取得指令方法
輸入指令可大致分為兩部分,一部份是「什麼指令」,另一部份是「資訊」。
問題是指令沒辦法單純以空白切割,也不一定是一個字。

方法: 使用getline()分割字串。

string cmd;
while (getline(cin, cmd))
{
stringstream ss(cmd);
getline(ss, cmd, '\"');
                // ......
        }
如此一來,就能取得「命令」的部分,即cmd。



二、解析指令的方法
方法: cmd.substr(pos, n) == 字串,pos為字串比對起始點,n為長度。

如此可在不破壞字串的情況下得到資訊。



三、 map, pair, set, typedef 的細節

解題結構如下:
typedef pair<string, string> B_Info; // title, author
typedef map<B_Info, set<int>> Books;
Books database;

如此一來,就能使用pair, map, set的特性快速存取、修改。

map 跟 set 都有count(),用來檢查有沒有某個資料。

typedef pair<string, string> B_Info 的意思是把 pair<string, string> 叫做 B_Info,這樣後面就不用每次都打 pair<string, string>,比較易讀也節省時間。


四、遍歷資料的細節
像是在輸出 edition 時,是用 set iterator 跑的。那要如何指定說像是: 第一個或最後一個資料輸出長的不一樣呢?

沒辦法像一般可以: 
for(int i=0; i< m.size();i++)
{
    if(i==m.size()-1) // do something.....
}
但可以:
if(it==m.begin()) {}


五、 sort map
如果想把 map 依照指定順序排列該怎麼做?

struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};

// ...
std::map<std::string, std::string, cmpByStringLength> myMap;



心得

在「預期解題時間」一欄,助教寫了35分鐘。我真心好奇助教是如何計算時間的,感覺光是照著最後寫出來的code打也要半個小時左右,考場上不能查資料、重無到有寫出來,大一學生總得要一個多小時吧。(還是我程度太差?)

沒有留言:

張貼留言