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

Blu*_*789 12 c++ variables null nullptr

我有三个LPCWSTR字符串变量叫A,B,C.

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

A = MyFunc();
B = MyFunc();
C = MyFunc();
Run Code Online (Sandbox Code Playgroud)

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

我自己尝试这样做:

if ((A == nullptr) && (B == nullptr) && (C <> nullptr)) {}
Run Code Online (Sandbox Code Playgroud)

有关如何做到这一点的任何想法都是受欢迎的

pax*_*blo 15

很容易做到:

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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

下一步将使用基于范围的for循环支撑的init列表,如下面的完整程序:

#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;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以通过使用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;
}
Run Code Online (Sandbox Code Playgroud)

然而,对于你的特殊情况,这可能是矫枉过正的:-)

  • 我之前从未在C++中看到过立即调用的lambda表达式...为什么不只是`for(const auto&pointer:{A,B,C,D,E,F}){...`? (4认同)
  • 你的编码风格......令人沮丧. (2认同)

Jar*_*d42 11

使用std,您可以:

const auto vars = {A, B, C}; // Create initializer list.
const bool onlyOneNotNull =
    (std::count(vars.begin(), vars.end(), nullptr) == (vars.size() - 1);
// then you may use find_if to retrieve the non null variable.
Run Code Online (Sandbox Code Playgroud)


Jes*_*uhl 7

这是一个简单的方法:

int not_null = 0;
not_null += A != nullptr;
not_null += B != nullptr;
not_null += C != nullptr;
if (not_null == 1) {
    /* Do stuff */
}
Run Code Online (Sandbox Code Playgroud)

检查每个是否存在nullptr,如果不是则增加计数.如果计数1最终出来,做你的事.