在Linux環境下使用C++ STL(Standard Template Library,標準模板庫)主要涉及以下幾個步驟:
確保你的Linux系統上安裝了支持C++11及以上標準的編譯器,如GCC或Clang。你可以使用以下命令來安裝GCC:
sudo apt update
sudo apt install g++
創建一個C++源文件,例如main.cpp,并在其中包含STL頭文件。以下是一個簡單的示例,展示了如何使用STL中的vector和algorithm:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// 使用STL算法排序
std::sort(vec.begin(), vec.end());
// 輸出排序后的向量
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
使用g++編譯你的C++代碼。確保啟用C++11或更高版本的支持:
g++ -std=c++11 -o my_program main.cpp
編譯成功后,運行生成的可執行文件:
./my_program
你應該會看到輸出:
1 1 2 3 3 4 5 5 5 6 9
vector:動態數組list:雙向鏈表deque:雙端隊列stack:棧queue:隊列priority_queue:優先隊列map:有序映射unordered_map:無序映射set:有序集合unordered_set:無序集合sort:排序search:搜索count:計數find:查找transform:轉換for_each:遍歷unique:去重map和set#include <iostream>
#include <map>
#include <set>
int main() {
std::map<std::string, int> ageMap = {
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35}
};
std::set<std::string> namesSet(ageMap.begin(), ageMap.end());
// 輸出map中的內容
for (const auto& pair : ageMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 輸出set中的內容
for (const auto& name : namesSet) {
std::cout << name << std::endl;
}
return 0;
}
通過以上步驟,你可以在Linux環境下輕松使用C++ STL。熟悉STL的容器和算法可以大大提高你的編程效率和代碼質量。