学好这 13 种数据结构,应对各种编程语言(C++ 版)

本文以C++为例,总结了13种重要的数据结构,包括数组、向量、双向链表、单链表、队列、双端队列、优先队列、堆、栈、映射、unordered_map、pair和tuple。理解这些数据结构有助于程序员在学习其他编程语言时更好地应对各种数据存储和处理需求。
摘要由CSDN通过智能技术生成

学了这么长时间数据结构和算法,有必要来个总结了,顺便回顾一下我们这段时间的学习成果。以 C++ 语言本身提供的数据结构为例。如果能掌握这 13 种数据结构,相信在学习其它语言的时候就不费劲了。 

数组 Array 

数组在初始化的时候就需要知道其大小,后续是不可以改变其大小的,可以通过下标来获取某个 index 中存放的元素。在 C++ 中通过源码可以知道,它其实是在 C 数组的基础上封装的: 

 

#include <array>

void testArray() {

// 创建一个数组

std::array<int, 5> a = {2, 4, 6, 8, 10};

// 对数组进行遍历

for (const auto i : a) {

std::cout << i << std::endl;

}

for(int i = 0; i < a.size(); i++) {

std::cout << a[i] << std::endl;

}

// 取第一个值,通过 [index] 获取

std::cout << "a[0] = " << a[0] << std::endl;

// 修改数组中第一个值

a[0] = 5;

/**

at 会检查 index 是否越界,越界将 crash,而 a[index] 不会;

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: array::at

*/

a.at(0);

// 数组是否为空

a.empty();

// 求数组的长度

std::cout << "a.size()=" << a.size() << std::endl;

// 获取第4个值

int value = std::get<4>(a);

std::cout << "a(4) = " << value << std::endl;

// 创建一个空数组,数组中的值为0或者是与类型相等的其它值

std::array<int, 5> a2;

std::cout << "end a2" << a2[0] << std::endl;

// 比较两个数组中的元素是否都相等

if (a == a2) {}

}

可变数组,向量vector

在C++中使用 Vector 存当可变数组,它的容量可以动态改变,初始化的时候不需要确定数组的大小。使用的方法和数组基本一致。

 

#include <vector>

// 向量

void testVector() {

/**

vector<T> 它与Array不同,它的大小是可变的

*/

std::vector<std::string> v;

// 增加容器的容量,至少容纳 20 个元素

v.reserve(20);

// 初始化一个向量

std::vector<int> v2 = {2, 4, 5, 7};

// 以数组初始化一个vector

std::array<std :: string, 5> words {"one", "two","three", "four", "five"};

std::vector<std::string> words_copy {std::begin(words) , std::end(words)};

// 通过 v[index] 获取或者修改元素

std::cout << "v[0] = " << v2[1] << std::endl;

// 获取第一个元素

std::cout 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值