3.2標準庫型別 string
練習3.5編寫一段程式從標準輸入中讀入多個字串並用空格分隔開
#include #includeusing std::string
;using
std::cin;
using
std::cout;
using
std::endl;
intmain()
cout
<< "
the concatenated string is
"<< largestr
練習3.11下面的範圍for語句合法嗎?如果合法,c的型別是什麼?
const string s = "keep out!";when you don't changefor (auto &c : s)
c
's value, it's legal, else it's illegal.
for example:
cout << c; // legal.
c = 'x'; // illegal.
the type ofc
isconst char&
. read-only variable is not assignable.
3.3標準庫型別vector
練習3.24:請使用迭代器重做3.3.3節的最後乙個練習(讀入一組整數並把他們存入乙個vector物件,先輸出第乙個和最後乙個元素的和,接著輸出第二個和倒數第二個元素的和,以此類推)
#include#includeusing
namespace
std;
intmain()
return0;
}
這是我做的第乙個版本,但是在stackoverflow上看到相同問題,發現沒有檢查vector是空的的情況。修改版:
#include #include#include
using std::vector; using std::cout; using std::endl; using
std::cin;
intmain()
else
if(ivec.size() == 1)
for (auto it = ivec.begin(); it+1 != ivec.end(); ++it)
cout
<< *it + *(it+1) << "";
cout
cout
<< *beg + *end << "";
cout
}
(form github)
練習3.26:在100頁的二分搜尋程式中,為什麼用的是mid=beg+(end-beg)/2,而非mid = (beg+end)/2?
不會產生比end大的中間資料,更安全
指標和迭代器不可相加但可相減。
第三章 字串 向量和陣列
標頭檔案不應包含using宣告。c 標準一方面對庫型別所提供的操作做了詳細規定,另一方面也對庫的實現者做出了一些效能上的需求。因此,標準庫型別對於一般應用場合來說有足夠的效率。如果使用等號 初始化乙個變數,實際上執行的是拷貝初始化 copy initialization 編譯器把等號右側的初始值拷貝...
第三章 字串 向量和陣列
1 以命名空間std為例,兩種宣告方式 1 using std cin 或cout,endl等 2 using namespace std 2 標頭檔案中不應包含using宣告。1 初始化的方式分為拷貝初始化 使用等號 與直接初始化 不使用等號 1 使用getline讀取一整行 直接讀只會讀乙個單詞...
第三章 字串 向量和陣列
標頭檔案 include string定義和初始化 string s1 string s1 s2 string s1 hello string s1 hello string s1 n,c string物件的操作 cin s1 cout cin,s1 s.empty s.size s n s1 s2...