一般來說,寫程式的時候,你不會想重新發明輪子。 許多標準演算法,可能早就有人幫你把工作做完了。
include 指令為了引入其他檔案的內容,C++ 使用 include 指令。
這些引入應該寫在檔案的開頭。
編譯期間,帶有這個指令的那一行會被替換成對應檔案的內容。
引入之後,命名空間會保持和原始檔案中一樣。
標準函式庫提供了許多常用的函式、演算法和資料結構。
標準函式庫使用 std 命名空間。
其中一個例子是 C 的數值函式庫 cmath。
它提供了許多常見的數學運算。
#include <cmath>
int cube_me(int a) {
// raise `a` to the third power
return std::pow(a, 3);
}
標準函式庫是用尖括號 <> 引入的,而不是雙引號 "。
差別在於編譯器搜尋對應檔案的位置。
使用尖括號的版本會跳過在目前專案中的搜尋,直接從系統的引入目錄開始找起。
如果你想引入本地檔案,就要用雙引號:#include "myfile"
在 C++ 中,string 是一個可變的物件,用一連串的字元(字母、數字、標點符號等)來表示文字。
字串是透過呼叫它的方法來操作的。
在 C++ 中,字串型別和相關的函式必須在使用前先從字串函式庫引入。
你可以在檔案開頭加上 #include <string> 來做到這點。
它們接著會被放進 std 命名空間。
字串型別的完整名稱是 std::string。
字串常值使用雙引號字元:"。
#include <string>
std::string w_berry_quote{"A well-made sentence, I think, is a thing of beauty."};
你可以用 + 運算子來串接字串:
std::string original_title{"The School of Rock"};
std::string sequel_indicator{"Electric Boogaloo"};
std::string next_movie_title = original_title + " 2: " + sequel_indicator;
要使用字串函式庫,你需要知道,可以呼叫屬於某個物件的函式。 這些函式稱為成員函式。 之後在教學大綱中,你會學到更多關於成員函式和相關類別概念的內容。
std::string qualification{"awesome"};
// 1st argument: from the index to the end of the string:
std::string who_is_awesome = qualification.substr(5);
// => "me"
// 2nd optional argument for the length:
std::string material{"haunted books"};
std::string ghost = material.substr(8, 3);
// => "boo"
find 函式也非常實用。
它是以成員函式的形式在字串上呼叫,並接受一個字串作為引數。
find 會回傳字串中_第一次_出現位置的索引,索引從零開始。
std::string new_release{"apple released a new app!"};
new_release.find("app");
// => 0
new_release.find("e");
// => 4
在這道練習中,你會處理日誌報告中的每一行。
每一行日誌都是格式如下的字串:"[<LEVEL>]: <MESSAGE>"。
日誌共有三種等級:
INFOWARNINGERROR你有三個任務,每個任務都會拿到一行日誌,並要你對它做點處理。
實作log_line::message方法,回傳日誌行的訊息:
log_line::message("[ERROR]: Invalid operation")
// => "Invalid operation"
實作log_line::log_level方法,回傳日誌行的日誌等級,而且要以大寫回傳:
log_line::log_level("[ERROR]: Invalid operation")
// => "ERROR"
實作log_line::reformat方法,重新格式化日誌行,把訊息放在前面,並在後面用括號標註日誌等級:
log_line::reformat("[INFO]: Operation completed")
// => "Operation completed (INFO)"