学了这么长时间数据结构和算法,有必要来个总结了,顺便回顾一下我们这段时间的学习成果。以 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