在Ubuntu中,C++可以使用標準模板庫(STL)中的各種容器。以下是一些常用的STL容器及其使用方法:
向量是一個動態數組,可以在運行時調整大小。要使用向量,需要包含頭文件<vector>。
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec; // 創建一個整數向量
// 添加元素
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
// 訪問元素
std::cout << "第一個元素: " << vec[0] << std::endl;
// 遍歷向量
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
return 0;
}
列表是一個雙向鏈表,可以在常數時間內插入和刪除元素。要使用列表,需要包含頭文件<list>。
#include <iostream>
#include <list>
int main() {
std::list<int> lst; // 創建一個整數列表
// 添加元素
lst.push_back(1);
lst.push_back(2);
lst.push_back(3);
// 訪問元素
std::cout << "第一個元素: " << lst.front() << std::endl;
// 遍歷列表
for (int num : lst) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
集合是一個有序的容器,其中的元素是唯一的。要使用集合,需要包含頭文件<set>。
#include <iostream>
#include <set>
int main() {
std::set<int> st; // 創建一個整數集合
// 添加元素
st.insert(1);
st.insert(2);
st.insert(3);
// 遍歷集合
for (int num : st) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
映射是一個鍵值對的容器,其中的鍵是唯一的。要使用映射,需要包含頭文件<map>。
#include <iostream>
#include <map>
int main() {
std::map<std::string, int> mp; // 創建一個字符串到整數的映射
// 添加元素
mp["one"] = 1;
mp["two"] = 2;
mp["three"] = 3;
// 訪問元素
std::cout << "one: " << mp["one"] << std::endl;
// 遍歷映射
for (const auto& pair : mp) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
這些只是STL容器的一部分。還有其他容器,如deque(雙端隊列)、stack(棧)、queue(隊列)等。要使用這些容器,請查閱C++標準庫文檔以獲取更多信息。