stl常用容器说明

容器特点

  • vector :动态数组,内存连续,支持随机访问([]),尾部插入/删除 O(1),中间插入/删除 O(n)。
  • list:双向链表,内存不连续,不支持随机访问,任意位置插入/删除 O(1)。
  • set:有序集合,元素唯一且自动升序,基于红黑树,插入/查找/删除 O(log n)。
  • map :有序键值对,键唯一且自动按键升序,基于红黑树,[] 和插入/查找/删除 O(log n)。
  • unordered_map:无序键值对,键唯一,基于哈希表,平均插入/查找/删除 O(1),最坏 O(n)。

代码

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;
}

输出结果

相关推荐
小七在进步3 小时前
string的使用(1)
c++·visual studio
SomeOtherTime3 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood3 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青4 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
kloc7 小时前
聊天室项目入口网关子服务的实现
linux·c++
饮水桶_T7 小时前
JAVA IO流笔记
开发语言·数据结构·算法
csdn_aspnet10 小时前
C++ 3个有序点的方向(Orientation of 3 ordered points)
c++·算法
Felven10 小时前
C. Brr Brrr Patapim
c语言·开发语言
小七在进步11 小时前
string的使用(2)
c++
路溪非溪11 小时前
python标准库使用总结
开发语言·python