cpp
复制代码
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<unordered_map>
#include<list>
using namespace std;
int main() {
//vector:动态数组。 特点:内存连续,支持随机访问,尾部插入高效
vector<int> vec= {1, 2, 3};
vec.push_back(4); // 在数组末尾添加元素4,时间复杂度:O(1)
// list:双向链表。特点:内存不连续,插入删除高效,不支持随机访问
list<int> list = { 10,20,30 };
list.push_front(5);// 在链表头部插入元素5
set<int> s = { 5,2,3,3 };
map<string, int> m = { {"Tom",11} ,{"jerry",22}};
unordered_map<string, int> um;
um["apple"] = 3;
um["banana"] = 5;
//====================输出=================================
cout << "vec[3]:" << vec[3] << endl;
cout << "list第一个元素:" << list.front() << endl;
cout << "set全部元素:";
for (int i : s) {
//cout << s[i] << " ";//错误写法
cout << i << " ";
}
cout << endl;
cout << "map:";
for (auto it = m.begin(); it != m.end(); it++) {
cout << it->first << ":" << it->second << endl;
}
//pair.first → 键(key):这里是 string 姓名
//pair.second → 值(value):这里是 int 年龄
for (auto& pair : m) {
cout << pair.first << ":" << pair.second << endl;
}
cout << "unordered_map:" << endl;
for (auto& kv : um) {
cout << kv.first << ":" << kv.second << endl;
}
//cout << "list[0]:" << list[0] << endl;
// // list:双向链表,不支持[],必须用迭代器/front()
return 0;
}