在Ubuntu上使用C++ STL(Standard Template Library)庫非常簡單,因為這些庫已經預裝在大多數Linux發行版中。以下是如何在Ubuntu上使用C++ STL庫的步驟:
打開終端: 打開你的Ubuntu系統的終端。
創建或打開C++源文件:
使用文本編輯器(如nano、vim或gedit)創建一個新的C++源文件,或者打開一個已有的文件。例如,使用nano編輯器創建一個名為main.cpp
的文件:
nano main.cpp
編寫C++代碼:
在源文件中編寫你的C++代碼,并包含必要的STL頭文件。例如,如果你想使用vector
和iostream
,你的代碼可能看起來像這樣:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
編譯代碼: 使用g++編譯器編譯你的C++代碼。在終端中輸入以下命令:
g++ -o myprogram main.cpp
這里,-o myprogram
指定了輸出的可執行文件的名稱為myprogram
。
運行程序: 編譯成功后,運行生成的可執行文件:
./myprogram
你應該會看到輸出:
1 2 3 4 5
容器:
vector
:動態數組list
:雙向鏈表deque
:雙端隊列stack
:棧queue
:隊列priority_queue
:優先隊列map
:關聯數組(紅黑樹)set
:集合unordered_map
:無序關聯數組unordered_set
:無序集合算法:
sort
:排序search
:搜索count
:計數find
:查找transform
:轉換for_each
:遍歷map
和sort
以下是一個使用map
和sort
的示例代碼:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
std::map<std::string, int> ageMap = {
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35}
};
// 將map中的元素復制到vector中以便排序
std::vector<std::pair<std::string, int>> vec(ageMap.begin(), ageMap.end());
// 按年齡排序
std::sort(vec.begin(), vec.end(), [](const auto& a, const auto& b) {
return a.second < b.second;
});
// 輸出排序后的結果
for (const auto& p : vec) {
std::cout << p.first << " " << p.second << std::endl;
}
return 0;
}
編譯并運行這個程序,你會看到按年齡排序的輸出:
Bob 25
Alice 30
Charlie 35
通過這些步驟和示例,你應該能夠在Ubuntu上輕松使用C++ STL庫。