gpt4 book ai didi

c++ - 检查 C++ 中是否只有一个字符串变量不是 nullptr

转载 作者:IT老高 更新时间:2023-10-28 23:03:51 25 4
gpt4 key购买 nike

我有三个 LPCWSTR 字符串变量,分别称为 ABC

我从另一个函数分配它们,如果出现问题,有时会返回 nullptr。像这样:

A = MyFunc();
B = MyFunc();
C = MyFunc();

现在,对于带有这些变量的一些东西,我需要检查这些变量中是否只有一个不是 nullptr(只分配了一个变量)。

我自己尝试这样做:

if ((A == nullptr) && (B == nullptr) && (C <> nullptr)) {}

欢迎任何关于如何做到这一点的想法。

最佳答案

很容易做到:

int numSet = 0;
A = MyFunc(); if (A != nullptr) numSet++;
B = MyFunc(); if (B != nullptr) numSet++;
C = MyFunc(); if (C != nullptr) numSet++;
if (numSet == 1) // only one is set

您还可以使用辅助函数封装该行为:

LPCWSTR MyFuncWithCount(int &countSetProperly) {
LPCWSTR retVal = MyFunc();
if (retVal != nullptr) countSetProperly++;
return retVal;
}

int numSet = 0;
A = MyFuncWithCount(numSet);
B = MyFuncWithCount(numSet);
C = MyFuncWithCount(numSet);
if (numSet == 1) // only one is set

下一步将使用 基于范围的 for 循环花括号初始化列表,按照以下完整程序:

#include <iostream>
#include <vector>

typedef void * LPCWSTR; // Couldn't be bothered including Windows stuff :-)

int main() {
// Only set two for test purposes.

LPCWSTR A = nullptr, B = nullptr, C = nullptr;
LPCWSTR D = &A, E = nullptr, F = &A;

int numSet = 0;
for (const auto &pointer: {A, B, C, D, E, F})
if (pointer != nullptr)
numSet++;

std::cout << "Count is " << numSet << std::endl;
}

或者您可以通过使用 lambda 函数来拥抱现代 C++ 的所有荣耀,如下所示:

#include <iostream>
#include <vector>

typedef void * LPCWSTR; // Couldn't be bothered including Windows stuff :-)

int main() {
// Only set two for test purposes.

LPCWSTR A = nullptr, B = nullptr, C = nullptr;
LPCWSTR D = &A, E = nullptr, F = &A;

int numSet = 0;
[&numSet](const std::vector<LPCWSTR> &pointers) {
for (const auto &pointer: pointers)
if (pointer != nullptr)
numSet++;
} (std::vector<LPCWSTR>{A,B,C,D,E,F});

std::cout << "Count is " << numSet << std::endl;
}

对于您的特定情况,这可能有点矫枉过正:-)

关于c++ - 检查 C++ 中是否只有一个字符串变量不是 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com