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

输出结果

相关推荐
biter down5 小时前
14:pytest-order 插件 顺序控制案例
开发语言·python·pytest
郝学胜-神的一滴5 小时前
Qt 高级开发 009: C++ Lambda 表达式
开发语言·c++·qt·软件构建
星栈独行6 小时前
我在 Rust 全栈项目里用 JWT 做无状态认证
开发语言·后端·rust·前端框架·开源·github·web
石山代码6 小时前
C++ 轻量级日志系统
开发语言·c++
小技与小术6 小时前
玩转Flask
开发语言·python·flask
SilentSamsara7 小时前
Python 性能优化:tracemalloc、profiling 与 C 扩展加速
开发语言·python·青少年编程·性能优化
冰小忆7 小时前
大驼峰命名规范和小驼峰命名规范的区别是什么?
开发语言·python
এ慕ོ冬℘゜8 小时前
JS 前端基础面试题
开发语言·前端·javascript
浩少7028 小时前
【无标题】
java·开发语言
nnsix9 小时前
C# 字符串 根据换行符分割
开发语言·c#