【C++】《C++ 17 入门经典》读书笔记 19 ---- std::optional

一、概述

在 C++17 中,标准库提供了 std::optional<>,它可以替代可选值的隐式编码。如:通过使用这种辅助类型,可以使用 optional<int>显式声明任何可选的 int 值。如下所示:

optional<int> find_last_in_string(string_view string, char to_find, optional<int> start_index);
optional<int> read_configuration_override(string_view fileName, string_view overrideName);

现在就显式地将这些参数或返回值声明为可选值,使得函数原型的意义更加清晰。因此,相比使用传统的方法,代码变量更加容易使用和阅读。

二、示例程序

特别注意:由于本示例代码中使用到 C++17 中的新特性:optional 、 string_view。目前 Visual Studio 2017 (15.9.14) 尚不支持,我是在 Visual Studio 2019 (16.2.0) 中编译执行的。

这个示例程序中展示 std::optional<> 基本用途:

#include <iostream>
#include <optional>
#include <string_view>

using namespace std;

optional<size_t> find_last(string_view string, char to_find, optional<size_t> start_index = nullopt)
{
	if (string.empty())
		return nullopt;

	size_t index = start_index.value_or(string.size() - 1);

	while (true)
	{
		if (string[index] == to_find) return index;
		if (index == 0) return nullopt;
		--index;
	}
}

int main()
{
	const auto string = "Growing old is mandatory; growing up is optional.";
	
	const optional<size_t> found_a{ find_last(string, 'a') };
	if (found_a)
		cout << "Found the last a at index " << *found_a << endl;

	const auto found_b{ find_last(string, 'b') };
	if (found_b)
		cout << "Found the last b at index " << found_b.value() << endl;

	const auto found_early_i(find_last(string, 'i', 10));
	if (found_early_i != nullopt)
		cout << "Found an early i at index " << *found_early_i << endl;
}

说明:

  1. 注意:如何检查 find_last 返回的 optional<> 值是否被实际赋值。
  2. 注意:如何从 optional<> 中提取并使用这个值。
  3. value_or():如果 optional<> start_index 包含值,该函数返回的值与 value() 相同;如果不包含值, value_or() 将返回作为实参传入的值。因此,value_or() 是一个非常好的函数,相当于首先调用 has_value(),然后调用 value() 的 if-else 语句或条件运算符表达式。

三、运行输出

 


 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值