C++ optional用法入门

这篇博客探讨了C++中的optional对象,包括如何使用swap交换optional对象的值,利用value_or获取默认值,以及reset重置optional对象。示例代码展示了这些操作的用法,有助于理解optional在实际编程中的应用。
#include <iostream>
#include <optional>
#include <stdio.h>
using namespace std;

void swap() {
	optional<int> a = optional<int>(10);
	optional<int> b = optional<int>(11);
	a.swap(b);
	printf("a has value: %d\n", a.value());
	printf("b has value: %d\n", b.value());
}

void value_or() {
	optional<int> a = optional<int>();
	printf("a.value_or : %d\n", a.value_or(100));
	a = 11;
	printf("a.value_or : %d\n", a.value_or(100));
}

void reset() {
	optional<int> a = optional<int>(10);
	if (a) {
		printf("a has value: %d\n", a.value());
	} else {
		printf("a has no value\n");
	}
	a.reset();
	if (a) {
		printf("a has value: %d\n", a.value());
	} else {
		printf("a has no value\n");
	}
}

int main() {
	swap();
	value_or();
	reset();
	return 0;

}

#include <iostream>
#include <sstream>
#include <cassert>
#include <array>
#include <limits>
#include <set>
#include <unordered_map>
#include <functional>
#include <memory>
#include <ostream>
#include <string>
#include <vector>
#include <map>
#include <optional>
#include <chrono>
#include <mutex>
#include <thread>
#include <utility>
#include <typeinfo>
#include <queue>

using namespace std;

std::optional<int> baby()
{
  int a = 2;
  if (a > 1)
    return {};
  else
    return 3;
}

int main()
{
  auto s = baby();
  if (s.has_value())
  {
    cout << "I have baby" << endl;
    cout << s.value() << endl;
  }
  else
  {
    cout << "I have no  baby" << endl;
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值