C++ 的 optional类型

等级 5388 次按键

findIndex 返回 optional<int>:找到时为索引,找不到时为 nullopt。调用方先用 has_value() 检查再读取 value();has_value() 为 false 时输出 0。

C++ 代码

// 返回类型表明结果可能不存在
1optional<int> findIndex(const vector<int>& v, int target) {
// 依次检查每个元素
2 for (int i = 0; i < v.size(); i++) {
// 找到:int 类型的 i 会自动包装成 optional
3 if (v[i] == target) return i;
4 }
// 未找到:nullopt 表示“没有值”
5 return nullopt;
6}
7
8vector<int> nums = {10, 20, 30, 40, 50};
9
// 带初始化语句的 if(C++17):idx 只在这个 if 内有效
10if (auto idx = findIndex(nums, 30); idx.has_value()) {
// value() 读取索引,输出“Found at index: 2”
11 cout << "Found at index: " << idx.value() << endl;
12}
13
// 99 不在 vector 中,因此为 nullopt
14auto missing = findIndex(nums, 99);
// 没有 boolalpha 时 false 输出为 0:“Has value: 0”
15cout << "Has value: " << missing.has_value() << endl;

运行结果

Found at index: 2
Has value: 0
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 16
  • (× 10
  • )× 10
  • ;× 9
  • ,× 7
  • =× 6
  • .× 4
  • "× 4
  • {× 4
  • }× 4

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习