3
对标准库的扩充:新增容器*
std::array 和 std::forward_list*
std::array*
看到这个容器是肯定会出现这样的问题:
- 为什么要引入
std::array而不直接使用std::vector? - 已经有了传统数组,为什么要用
std::array?
第一个问题,std::vector 很强大,以至于我们往往不需要那么多功能。使用 std::array 保存在栈内存中,相比于堆内存中的 std::vector,我们能够灵活的访问里面的元素,从而获得更高的性能;同时也免去要释放堆内资源。
第二个问题,使用 std::array 能够使代码更加现代,且封装了一些操作函数,还能友好地使用标准库中的容器算法等,比如 std::sort。
std::array 会在编译器创建一个固定大小的数组,不能够被隐式地转换成指针,使用 std::array 很简单,只需指定其类型和大小即可:
std::array<int, 4> arr= {1,2,3,4};
int len = 4;
std::array<int, len> arr = {1,2,3,4}; // 非法, 数组大小参数必须是常量表达式
使用 std::array 时,难免会遇到要将其兼容 C 风格的接口,有以下几种做法:
void foo(int *p, int len) {
return;
}
std::array<int 4> arr = {1,2,3,4};
// C 风格接口传参
// foo(arr, arr.size()); // 非法, 无法隐式转换
foo(&arr[0], arr.size());
foo(arr.data(), arr.size());
// 使用 `std::sort`
std::sort(arr.begin(), arr.end());
std::forward_list*
std::forward_list 是一个列表容器,使用方法和 std::list 基本类似。
使用单向链表实现,提供了 O(1) 复杂度的元素插入,不支持快速随机访问,也是标准库容器中唯一一个不提供 size() 方法的容器。当不需要双向迭代时,具有比 std::list 更高的空间利用率。
无序容器*
传统 C++ 中的有序容器 std::map/std::set,这些容器内部通过红黑树进行实现,插入和搜索的平均复杂度均为 O(log(size))。在插入元素时,会根据 < 操作符比较元素大小并判断是否相同,并选择合适的位置插入到容器中。当对这个容器中的元素进行遍历时,输出结果会按照 < 操作符的顺序来逐个遍历。
而无序容器中的元素是不排序的,内部通过 hash 表实现,插入和搜索元素的平均复杂度为 O(constant),在不关心容器内部元素顺序时,能够获得显著的性能提升。
C++11 引入了两组无序容器:std::unordered_map/std::unordered_multimap 和 std::unordered_set/std::unordered_multiset。
它们的用法与原容器基本类似,比较 std::map 和 std::unordered_map:
#include <iostream>
#include <string>
#include <unordered_map>
#include <map>
int main() {
// 两组结构按同样的顺序初始化
std::unordered_map<int, std::string> u = {
{1, "1"},
{3, "3"},
{2, "2"}
};
std::map<int, std::string> v = {
{1, "1"},
{3, "3"},
{2, "2"}
};
// 分别对两种容器进行遍历
std::cout << "std::unordered_map" << std::endl;
for( const auto & n : u)
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
std::cout << std::endl;
std::cout << "std::map" << std::endl;
for( const auto & n : v)
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
输出为 :
std::unordered_map
Key:[2] Value:[2]
Key:[3] Value:[3]
Key:[1] Value:[1]
std::map
Key:[1] Value:[1]
Key:[2] Value:[2]
Key:[3] Value:[3]
元组 std::tuple*
传统 C++ 中,除了 std::pair 外,没有现成的结构能够用来存放不同类型的数据,且 std::pair 只能保存两个元素。
元组基本操作*
元组有三个核心函数:
std::make_tuple:构造元组std::get:获得元组某个位置的值std::tie:元组拆包
#include <tuple>
#include <iostream>
auto get_student(int id)
{
// 返回类型被推断为 std::tuple<double, char, std::string>
if (id == 0)
return std::make_tuple(3.8, 'A', "张三");
if (id == 1)
return std::make_tuple(2.9, 'C', "李四");
if (id == 2)
return std::make_tuple(1.7, 'D', "王五");
return std::make_tuple(0.0, 'D', "null");
// 如果只写 0 会出现推断错误, 编译失败
}
int main()
{
auto student = get_student(0);
std::cout << "ID: 0, "
<< "GPA: " << std::get<0>(student) << ", "
<< "成绩: " << std::get<1>(student) << ", "
<< "姓名: " << std::get<2>(student) << '\n';
double gpa;
char grade;
std::string name;
// 元组进行拆包
std::tie(gpa, grade, name) = get_student(1);
std::cout << "ID: 1, "
<< "GPA: " << gpa << ", "
<< "成绩: " << grade << ", "
<< "姓名: " << name << '\n';
}
std::get 除了使用常量获取元组对象外,C++14 增加了使用类型获取元组对象:
std::tuple<std::string, double, double, int> t("123", 4.5, 6.7, 8);
std::cout << std::get<std::string>(t) << std::endl;
std::cout << std::get<double>(t) << std::endl; // 非法, 引发编译期错误
std::cout << std::get<3>(t) << std::endl;
运行期索引*
std::get<> 依赖一个编译器的常量,所以下面的方法是不合法的:
int index = 1;
std::get<index>(t);
C++17 使用 std::variant 可以解决。
元组合并与遍历*
还有一个常见需求就是合并两个元组,可以通过 std::tuple_cat 实现:
auto new_tuple = std::tuple_cat(get_student(1), std::move(t));
如何快速遍历一个元组,解决了运行期通过非常量索引,那么遍历元组就简单了。元组长度 std::tuple_size。
总结*
本节简单介绍了 C++11/14 中新增的容器,用法和传统 C++ 中已有的容器类似,相对简单,可以根据实际场景丰富地选择需要使用的容器,获得更好性能。
std::tuple 虽然有效,但是标准库提供的功能有限,无法满足运行期索引和迭代的需求。