讀書筆記 chapter1

2021-05-04 07:59:22 字數 2072 閱讀 9748

1. setw( size )的使用方法:

#include //setw(int asize)

const int nm_size = 128;

char user_name[ nm_size ];

cin >> setw( nm_size ) >> user_name;

如輸入的字元個數超過nm_size, 則取前nm_size -1 個字元給陣列,陣列中最後乙個元素自動設為空字元。

2. 利用cin 作為迴圈條件。

如vectorivec;

int ival;

while ( cin >> ival )

ivec.push_back( ival );

如果輸入非整數,則cin 返回 false, 迴圈結束。

同時在這幾條語句中我們也看到了vector的用法。ivec.push_back(ival).

3. isdigit(char c ) 的用法,判斷乙個字元是否是數字 0-9.

char a; char *p, p; string p;

isdigit( a ) 或 isdigit(p[0])

當a 或 p[0]為數字0-9時,返回非零值,否則返回零

4. vector 的元素是乙個字串指標,指向乙個字串

vector< string* > sp_vec;

string st;

while ( cin >> st && !( st.length() == 1 && st[0] == 『0』 ) )

sp_vec.push_back( new string( st ));

為什麼這裡要new 乙個 string 物件放到vector 中去?

因為要取多個string。

5. vector中的iterator

vector::iterator

iter = sp_vec.begin(),

it_end = sp_vec.end();

iter 將指向vector 中第乙個元素。

it_end將指向vector中最後乙個元素。

6. 檔案操作

string file_name;

cin >> file_name;

if ( ! cin || file_name.empty() )

ifstream ifile( file_name.c_str() ); //檔案必須存在,否則開啟失敗。

file_name += ".sort";//若檔案不存在,將建立乙個檔案。

ofstream ofile( file_name.c_str() );

seekg(0); 重定位檔案指標函式

讀取:  

string word;

vector< string > text;

while ( ifile >> word )

text.push_back( word );

排序: sort( text.begin(), text.end() );  // #include

輸出:int cnt = 0;

for ( vector::iterator iter = text.begin();   //定義了乙個指標iter,指向vector text中的元素。

iter != text.end(); ++iter )

cnt += iter->size()+1; // iter->size() 指該字串的長度

if ( cnt > 40 ) //每行小於40個字元

ofile << *iter << ' ';

普通的輸出方法:

for (int ix = 0; ix < text.size(); ++ix )

ofile << text[ ix ] << ' ';

7. 指標補充

定義乙個指標,指向乙個乙個陣列,定義乙個指向具有4個float元素的一維陣列的指標:float  (*p)[4]  //相當於二維陣列的陣列名

定義乙個陣列:vector *     p[4];  //陣列中的元素是:vector*

8.結束程式

#include

exit(-1);

CSSAPP 閱讀筆記 Chapter1

全書內容的粗略概括,對後續章節的內容在總體上有大致了解。程式的翻譯過程及編譯系統 預處理階段 預處理器 cpp 根據命令修改原始程式,得到以 i 作為副檔名的另乙個程式。編譯階段 編譯器 ccl 將文字檔案 i 翻譯成文字檔案 s 其中包含乙個組合語言程式。彙編階段 彙編器 as 將 s 檔案翻譯成...

課後習題Chapter1

相似之處 這兩個問題都是求最短的路徑 不同之處 最短路徑問題其實是給定了情景並且不需要遍歷所有的點只需要得到乙個點到另外乙個點的最短路徑就可以了,而旅行商人問題則需要遍歷所有的點並求得最短的路程,問題的複雜度不一樣。亦可以找到乙個最短的路徑,但是你無法找到乙個選擇一條送貨車行駛距離最短的送貨順序。其...

Chapter 1 內容梳理

目錄標準輸入與標準輸出 定位符號 scope operator 換行符號 endl 如何輸入eof 類,型別,成員,物件,變數等概念間的關係 從標準輸入讀取 v1,v1 從標準輸出列印求和結果 include includeint main std cout v2 std cout 輸出標準輸入與輸...