map迷人之處在於一次存key和value兩個值,且key是唯一的,但若遇到key可重複的情況呢?STL另外提供了multimap...
這是我修C++ Lab的題目,讓我們練習使用multimap,但其中能有許多小技巧值得學習:
Write a program to read, parse and insert the entries containing author-title records (file books-11-30-2006.txt). Insert the author-title pairs into a std:multimap. Your ouputs should look like:
1
key: Elisa Bertino value: Object-Oriented Database Systems
2
key: Jeffrey D. Ullman value: Principles of Database Systems, 2nd Edition
3
key: Jeffrey D. Ullman value: A First Course in Database Systems
4
key: Jeffrey D. Ullman value: Principles of Database and Knowledge-Base Systems
5
key: R. G. G. Cattell value: Object Data Management: Object-Oriented and Extended Relational Database Systems
6
key: Stanley B. Lippman value: C++ Primer, 4th Edition
7
請按任意鍵繼續 . . .
2
3
4
5
6
7
原本的books-11-30-2006.txt文字檔內容如下
1
author = {Jeffrey D. Ullman}, title = {Principles of Database Systems, 2nd Edition}
2
3
author = {Elisa Bertino}, title = {Object-Oriented Database Systems}
4
5
author = {Jeffrey D. Ullman}, title = {A First Course in Database Systems}
6
7
author = {R. G. G. Cattell}, title = {Object Data Management: Object-Oriented and Extended Relational Database Systems}
8
9
author = {Jeffrey D. Ullman}, title = {Principles of Database and Knowledge-Base Systems}
10
11
author = {Stanley B. Lippman}, title = {C++ Primer, 4th Edition}
2
3
4
5
6
7
8
9
10
11
程式碼如下
1
}
一般人處理字串,都會使用find()或find_last_of(),最後搭配substr(),32行使用StringStream來處理字串。StringStream的好用在於使用了<<和>>方式處理字串,而且可自動轉型,不需考慮型別,第32行,由於author = 這兩個字串並不是我們想處理的,可以將其>>到dump忽略之, 因為只想處理{}中間的值,所以使用find()找到'{'和'}',將中間的值湊成author StringStream。
66行為新增multimap的方式,要新增multimap,只有insert()搭配makepair一種方式而已,不像map可以使用subscripting的方式。