How to use StringStream(sstream) in C++ STL (UVA:482)
Perface
由於前幾天在CPE考試上每題都需要string 轉型成 int, 寫到整個腦溢血後痛定思痛決定要把幾百年前懶得看得StringStream拿出來複習一遍,所以才有了這個網誌和這篇文章。
Main
StringStream 是用來處理String type轉換問題的 Libery 使用前需要引用sstream Header File。
由於第一次使用MarkDown還在熟悉語法所以就簡短的打打而已,有興趣的話就自己去看它的Reference吧!
[1]
- string to int
|
|
透過ss,9192631770就會依序存取到整數陣列int_arry裡面了
- int to string
|
|
單純的把9192631770轉換成字串
Example
###UVA:482
Permutation Arrays
In many computer problems, it is necessary to permute data arrays. That is, the data in an array must be re-arranged in some specified order. One way to permute arbitrary data arrays is to specify the permutations with an index array to point out the position of the elements in the new array. Let x be an array that is to be permuted and let x’ be the permuted array. Then, we have the relationship between x and x’ that x’pi = xi.
Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
Each input set will contain two lines of numbers. The first line will be an index array p containing the integers 1…n, where n is the number of integers in the list. The numbers in the first line will have been permuted in some fashion. The second line will contain a list numbers in floating point format.
Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
The output for this program will be the list of floating point numbers from the input set, ordered according to the permutation array from the input file. The output numbers must be printed one per line in the same format in which they each appeared in the input file.
Sample Input
1
3 1 2
32.0 54.7 -2
Sample Output
54.7
-2
32.0
測資我是用makefile直接丟進來的,所以程式裡沒有讀檔。此外需要注意的是sstream會把.0的小數部分省略,
怕麻煩的話就直接當成字串處理吧。
|
|
Output:
54.7
-2
32
為了避免32.0的.0被捨去,所以直接用字串對應會是更好的選擇。
將15行的float f[100]; 改寫成 string f[100];
|
|
Output:
54.7
-2
32.0
Reference
Reference StringStream http://www.cplusplus.com/reference/sstream/stringstream/ [1]
Morris’ Blog http://morris821028.github.io/ [2]