在Linux環境下使用C++ STL(Standard Template Library,標準模板庫)主要涉及以下幾個步驟:
確保你的Linux系統上安裝了支持C++11及以上標準的編譯器,如g++
。
sudo apt update
sudo apt install g++
創建一個.cpp
文件,例如main.cpp
,并在其中編寫使用STL的代碼。
#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
map
和set
#include <iostream>
#include <map>
#include <set>
int main() {
std::map<std::string, int> ageMap = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 35}};
std::set<int> uniqueAges;
// 將map中的年齡插入到set中
for (const auto& pair : ageMap) {
uniqueAges.insert(pair.second);
}
// 輸出set中的年齡
for (int age : uniqueAges) {
std::cout << age << " ";
}
std::cout << std::endl;
return 0;
}
通過以上步驟,你可以在Linux環境下輕松使用C++ STL。STL提供了豐富的容器和算法,能夠大大提高編程效率和代碼的可讀性。不斷實踐和探索STL的各種功能,將有助于你更好地掌握C++編程。