当前位置: 首页 > news >正文

【C++】STL(1) - 序列容器

文章目录

  • 1. 一些概念
    • 1.1 STL容器类型
    • 1.2 补充
  • 2. vector
    • 2.1 基本用法
      • 2.1.1 创建
      • 2.1.2 访问
      • 2.1.3 增删改
      • 2.1.4 查找
      • 2.1.4 排序
      • 2.1.5 其他操作
    • 2.2 二维数组
    • 2.3 补充
  • 3. list
    • 3.1 forward_list:单链表
    • 3.2 list:双链表
  • 4. array
  • 5. deque
  • 6. 元组
    • 6.1 二元组pair
    • 6.2 多元组tuple
      • 6.2.1 创建和初始化
      • 6.2.2 tuple元素为引用类型时用例
      • 6.2.3 基本操作

1. 一些概念

1.1 STL容器类型

序列容器:线性数据结构容器。

  • 数组:vector(动态大小,随机访问,尾部高效插入删除)),array(固定大小,随机访问)。
  • 链表:forward_list(单链表),list(双链表)。
  • 双端队列:deque(动态大小,随机访问,头尾高效插入删除)。

关联容器:非线性数据结构容器。可分为有序关联容器和无序关联容器。

  • 有序关联容器:set(不重复元素的集合),multiset(可重复元素的集合),map(不重复key的字典),multimap(可重复key的字典)

  • 无序关联容器:unordered_set,unordered_multiset,unordered_map,unordered_multimap

适配器:序列容器和关联容器称为首类容器,适配器是基于首类容器进行封装出来的容器。stack,queue,priority_queue

1.2 补充

  • 近似容器(near container):基于指针的数组;bitset;valarray

  • tuple不属于STL容器。

2. vector

2.1 基本用法

2.1.1 创建

创建vector会先分配一定容量,插入时如果容量不够,则申请现有容量的2倍再执行插入操作

#include <vector>
vector < int > v0;				  // 初始大小为0
vector < int > v1(10);			  // 初始大小为10,默认元素值为0
vector < int > v2(10, 1);		  // 初始大小为10,指定初始值为1
vector < int > v3 = { 1, 2, 3 };  // 使用初始化列表初始化vector对象
vector < int > v4(v3);			  // 用一个vector初始化另一个vector

// 基础信息:长度,容量,最大容量
cout << "size: " << vec.size() << endl;			// 数组长度
cout << "capacity: " << vec.capacity() << endl;	// 当前给数组分配的容量
cout << "max_size: " << vec.max_size() << endl; // 数组最大长度,固定

/*
v0: size=0, capacity=0, max_size=4611686018427387903
v1: size=10, capacity=10, max_size=4611686018427387903
v2: size=10, capacity=10, max_size=4611686018427387903
v3: size=3, capacity=3, max_size=4611686018427387903
v4: size=3, capacity=3, max_size=4611686018427387903
*/

v3.push_back(4);  // v3: size=4, capacity=3*2=6

2.1.2 访问

// 遍历所有元素1:下标法
vector<int> arr(10, 1)
for(auto i = 0; i <arr.size3(); ++i){
    cout << arr[i];
}

// 遍历所有元素2:迭代器法
for(auto it = arr.begin(); it != arr.end(); it++){
    cout << *it;
}

// 遍历所有元素3:采用输出迭代器
ostream_iterator<int> output( cout, " " );  // #include <iterator>
copy( arr.cbegin(), arr.cend(), output );  	// #include <algorithm>


// 访问单个元素1:下标法
cout << arr[2];

// 访问单个元素2:at()方法
cout << arr.at(2);

// 访问单个元素3:迭代器
auto it = arr.begin();
cout << *(it + 2);

// 访问单个元素:首元素
cout << arr.front();
    
// 访问单个元素:尾元素
cout << arr.back()

2.1.3 增删改

// 插入:指定位置插入单个元素
vector<int> arr(3, 1);
vector<int> arr1(2, -1);
int pos = 1;
arr.insert(arr.begin() + pos, 0);		 			// arr = {1, 0, 1, 1}
// 插入:指定位置插入多个元素
arr.insert(arr.begin() + pos, 3, 2);				// arr = {1, 2, 2, 2, 0, 1, 1}
arr.insert(arr.begin(), arr1.begin(), arr1.end());	// arr = {-1, -1, 1, 2, 2, 2, 0, 1, 1}
arr.insert(arr.begin(), {3, 3});  					// arr = {3, 3, -1, -1, 1, 2, 2, 2, 0, 1, 1}
// 插入:尾部插入单个元素
arr.push_back( 4 );  								// arr = {3, 3, -1, -1, 1, 2, 2, 2, 0, 1, 1, 4}

// 删除:指定位置删除单个元素
pos = 3;
arr.erase(arr.begin() + pos);						// arr = {3, 3, -1, 1, 2, 2, 2, 0, 1, 1, 4}
// 删除:指定位置删除多个元素
arr.erase(arr.begin() + pos, arr.begin() + pos + 2);// arr = {3, 3, -1, 2, 2, 0, 1, 1, 4}
// 删除:尾部删除单个元素
arr.pop_back();										// arr = {3, 3, -1, 2, 2, 0, 1, 1}

// 修改
arr[2] = -2;										// arr = {3, 3, -2, 2, 2, 0, 1, 1, 4}

2.1.4 查找

// 使用algorithm库中的find函数
#include <algorithm>
using namespace std;

vector<int> arr = {1, 2, 3, 4, 5};
auto it = find(arr.begin(), arr.end(), 3);
if(it != arr.end()){
    cout << "find elem: " << *it << endl;
} else {
    cout << "not found!" << endl;
}

// 手动遍历找,略

2.1.4 排序

// 使用sort升序排序(基本数据类型)
vector<int> arr(10) = {7, 5, 3, 4, 1, 2, 6, 9, 8, 10};
sort(arr.begin(), arr.end());

// 自定义排序:降序
bool compareDesc(int a, int b) {
    return a > b;
}
sort(arr.begin(), arr.end(), compareDesc);

// 使用lambda表达式:降序
sort(arr.begin(), arr.end(), [](int a, int b) {
    return a > b;
});

// 稳定排序
stable_sort(arr.begin(), arr.end());

2.1.5 其他操作

// 判断是否为空
if( arr.empty() ){
    cout << "arr is empty!" << endl;
}

// vector对象的比较
vector < int > a1(7);
vector < int > a2(7);
if ( a1 == a2 )  // a != b
    cout << " vector a1 is eqaul vector a2";

// 清空vector
arr.clear();			 // 会调用erase方法,size=0, capacity不变

// 缩放vector
vector<int> arr(2, 1);  // size=2, capacity=2
arr.resize(5);			// 扩充时capactity不够,默认扩充元素为0:arr=[1,1,0,0,0], size=5, capacity=5
arr.resize(2);			// 缩小不改变capacity:arr=[1,1], size=2, capacity=5
arr.resize(3, 2);		// 扩充时capacity够,指定扩充元素为2:arr=[1,1,2], size=3, capacity=5
arr.shrink_to_fit();	// 将capacity值调整为 capacity = size = 3

2.2 二维数组

#include <vector>
const int rows = 5;
const int cols = 5;
vector<vector<int>> mat(rows, vector<int>(cols, 1));  // 全1的5×5矩阵

for(size_t i=0; i<mat.size(); i++){
    for(size_t j =0; j<mat.size(); j++){
        cout << mat[i][j] << " ";
    }
    cout << endl;
}

for(auto row = mat.begin(); row != mat.end(); row++){
    for(auto elem = row->begin(); elem != row->end(); elem++){
        cout << *elem << " ";
    }
    cout << endl;
}

2.3 补充

  • vector元素为指针时,erase函数会根据不同类型的指针采取不同的操作:如果元素是指向动态分配内存的指针,erase不删除动态内存;如果元素为unique_ptr,则erase会删除其指向的对象;如果元素为shared_ptr则erase不删除对象而将所指向对象的引用计数减1,引用计数为0才删除对象。
  • 相比于下标访问元素,调用at()方法访问元素可以使用捕获越界异常。STL常见的异常:out_of_range、invalid_argument、length_error、bad_alloc

3. list

3.1 forward_list:单链表

#include <forward_list>
forward_list<int> flist = {1, 3, 4};

// 插入: 指定位置之后插入
flist.insert_after(flist.begin(), 2);  		// {1,2,3,4}

// 插入:在头部插入
flist.push_front(0);  						// {0,1,2,3,4}

// 在容器内生成元素,避免调用拷贝或者移动构造函数
flist.emplace_front(-2);  					// {-2,0,1,2,3,4}
flist.emplace_after(flist.begin(), -1);  	// {-2,-1,0,1,2,3,4}

// 删除: 删除指定位置后的一个元素
flist.erase_after(flist.begin());			// {-2,0,1,2,3,4}

// 删除:删除首元素
flist.pop_front();							// {0,1,2,3,4}

// 查找:单链表只能顺序查找
int target = 3;
for(auto elem: flist){
    if( target == elem ){
        cout << "elem found!" << endl;    
    }
}

// 获取列表长度
size_t len = distance(flist.begin(), flist.end());
cout << "len: " << len << endl;

// 清空列表
flist.clear();

3.2 list:双链表

#include <list>
list<int> mylist0 = {1, 3, 4};
list<int> mylist1(3, 1);

// 插入:在头部插入元素
mylist0.push_front(0);				// {0,1,3,4}
// 插入:在尾部插入元素
mylist0.push_back(5);    			// {0,1,3,4,5}
// 插入:在指定位置插入元素
mylist0.insert(mylist0.begin(), -1); // {-1,0,1,3,4,5}

// 删除:删除首元素
mylist0.pop_front();				// {0,1,3,4,5}
// 删除:删除尾元素
mylist0.pop_back();					// {0,1,3,4}
// 删除:删除指定位置元素
mylist0.erase(mylist0.begin());		// {1,3,4}

// 查找:链表只能顺序访问
int target = 3;
for(auto elem: mylist0){
    if( target == elem ){
        cout << "elem found!" << endl;    
    }
}

// 清空list
mylist0.clear();

4. array

#include <array>

array<int, 10> arr0;  // 使用未定义的默认值初始化
array<int, 10> arr1 = {1, 2, 3};  // 剩余元素用0填充;如果元素类型为类类型,则会调用默认构造函数 

// 访问:下标
cout << arr1[0] << endl;
// 访问:at()方法
cout << arr1.at(1) << endl;
// 访问:迭代器
auto it = arr1.begin() + 2;
cout << *it << endl;

// 获取数组大小
cout << "size: " << arr1.size() << endl;

// 检查数组是否为空
if(arr1.empty()){
    cout << "arr1 is empty" << endl;
}

// 交换数组
for(auto i = 0; i<arr0.size(); i++ ){
    arr0[i] = i;
}
arr0.swap(arr1);
/*
交换前:arr0=[0,1,2,3,4,5,6,7,8,9]; arr1=[1,2,3,0,0,0,0,0,0,0]
交换后:arr0=[1,2,3,0,0,0,0,0,0,0]; arr1=[0,1,2,3,4,5,6,7,8,9]
*/

5. deque

#include <deque>
deque<int> dq0(3, 1);
deque<int> dq1={1, 2, 3};

// 访问:使用下标
cout << dq1[0] << ' ';
// 访问:使用at()方法
cout << dq1.at(1) << ' ';
// 访问:使用迭代器
auto it = dq1.begin() + 2;
cout << *it << endl;
// 访问:访问首元素
cout << dq1.front() << ' ';
// 访问:访问尾元素
cout << dq1.back() << ' ';

// 插入:在指定位置插入元素
dq1.insert(dq1.begin()+1, 0);
// 插入:在头部插入元素
dq1.push_front(0);
// 插入:在尾部插入元素
dq1.push_back(4);

// 删除:删除指定位置元素
dq1.erase(dq1.begin()+1);
// 删除:删除头部元素
dq1.pop_front();
// 删除:删除尾部元素
dq1.pop_back();

// 遍历1
for(auto elem: dq1){
    cout << elem << ' ';
}
cout << endl;
// 遍历2
for(auto it=dq1.begin(); it!=dq1.end(); it++){
    cout << *it << ' ';
}
cout << endl;

// 清空
dq1.clear();

// 获取长度
cout << dq1.size() << ' ';

// 判断是否为空
if( dq1.empty() ){
    cout << "empty" << endl;
}

6. 元组

6.1 二元组pair

pair<string, int> myPair0; // ("", 0)
pair<string, int> myPair1("pen", 20);
pair<string, int> myPair2={"pen", 5};
pair<string, int> myPair3 = make_pair("pensil", 2);

// 访问pair元素
cout << myPair1.first << ": " << myPair1.second << endl;

// 比较操作:多字段比较,即先比较first字段,再比较second字段
cout << "myPair1 > myPair2: " << (myPair1 > myPair2) << endl;  // 1: myPair1 > myPair2
cout << "myPair1 > myPair3: " << (myPair1 > myPair3) << endl;  // 0: myPair1 < myPair3,"pen" > "pensil"

// 作为函数返回值类型
pair<int, string> response(int request){
    if(request == 0){
        return {200, "OK!"};
    } else {
        return {400. "Error!"}
    }
}

// 交换pair
swap(myPair1, myPair2);

6.2 多元组tuple

6.2.1 创建和初始化

using namespace std;

tuple<T1, T2, ..., TN> t1;      
tuple<T1, T2, ..., TN> t2(v1, v2, ... TN);
tuple<T1&> t3(ref&);
make_tuple(v1, v2);

6.2.2 tuple元素为引用类型时用例

string name;

tuple<string &, int> tpRef( name, 27 );
get<0>(tpRef) = "aa"
cout << "name: " << name << endl;

6.2.3 基本操作

tuple<string, int> myTp( "Cg", 27 );
// 获取元素值,给出的索引需要是字面量,而不能是变量
auto tpElem = get<0>(myTp);

// 获取元素个数
int tpNum = tuple_size<decltype(myTp)>::value;

// 获取元素类型
tuple_element<1, decltype(myTp)>::type ages = get<1>(myTp);

// 解包tuple分量
string name;
int age;
tie( name, age ) = myTp;
// 解包操作忽略第二个int型分量,使用std::ignore占位
tie( name, ignore ) = myTp;
// 集合make_tuple和引用来解包tuple,将myTp中元素解包到变量name,age
auto myTp1 = make_tuple(red(name), ref(age)) = myTp;

// 元组的比较1:所有元素类型可比较,则整个元组可比较。比较运算符:>, <, ==, >=, <=
// 元组的比较2:存在不可比较的元素类型(自定义类型),需要自定义重载比较运算符号

相关文章:

  • 在C#的MVC框架framework项目的使用ajax,及源码下载
  • 织梦DedeCMS后台发布文章增加“顶”和“踩”默认随机值,并可后台修改
  • [Windows] OfficeAI 助手 v0.3.20(长期免费,本地支持WPS/Word联动)
  • Java多线程与高并发专题——在 Thread 中多个 ThreadLocal 是怎么存储的?
  • langgraph简单Demo(使用langserve实现外部调用)
  • 解码软件需求的三个维度:从满足基础到创造惊喜
  • UMA架构下的GPU 显存
  • 4、MySQL的存储引擎有哪些?【中高频】
  • 蓝桥杯篇---按键长按与双击
  • 机试准备最后一天
  • electron框架(1.0)认识electron和基础创建
  • Elasticsearch基础教程:从入门到上手
  • 大话数据结构第二章,算法笔记
  • Oracle 公布 Java 的五大新功能
  • Vue安装及首次运行报错的相关问题解决方案
  • 二叉树(堆)
  • CentOS系统下安装tesseract-ocr5.x版本
  • Node.js 包与 npm 详解:概念、作用及完整使用指南
  • Android14 系统左右声音通道设置代码
  • 今天你学C++了吗?——二叉搜索树
  • 上海国际电影节纪录片单元,还世界真实色彩
  • “大鼻子情圣”德帕迪约因性侵被判缓刑,还有新的官司等着他
  • 中巴续签双边本币互换协议,进一步深化金融战略合作
  • 中国巴西关于乌克兰危机的联合声明
  • 福州千余公共道路泊车位装“智能地锁”续:运营公司被责令改正并罚款
  • 外交部:中方愿根据当事方意愿,为化解乌克兰危机发挥建设性作用