C ++根据条件初始化变量 [英] C++ initialize variable based on condition

查看:59
本文介绍了C ++根据条件初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试弄清楚如何根据条件初始化变量.这是我要修改的当前代码:

I am currently trying to figure out how to initialize variables based on conditions. So this is the current code that I want to modify:

int dimsOut[4];
dimsOut[0] = data->nDataVar();
dimsOut[1] = dims[0];
dimsOut[2] = dims[1];
dimsOut[3] = dims[2];

const size_t dataSize = data->primType().getTypeSize() * dimsOut[0] * dimsOut[1] * dimsOut[2] * dimsOut[3];

由于这是一个大型项目的一部分(大部分是C ++ 98,其中包括C ++ 03的某些部分),所以我想尽量减少修改,以免在其余代码中出现任何问题.所以我想做的只是在 data-> nDataVar()返回1的情况下执行上面的代码,并在返回其他内容的情况下执行基本上做到这一点

Since this is part of a giant project (mostly C++98 with some parts of C++03) I want to try to modify as less as possible to avoid any problems in the rest of the code. So what I want to do is simply in case data->nDataVar() returns 1 that the code above executes and in case it returns something else it should basically do this

int dimsOut[3];
dimsOut[0] = data->nDataVar();
dimsOut[1] = dims[0];
dimsOut[2] = dims[1];

const size_t dataSize = data->primType().getTypeSize() * dimsOut[0] * dimsOut[1] * dimsOut[2];

我知道无法使用if语句,因为变量将超出范围.

I am aware that it is not possible to use if-statements since the variables would go out of scope.

我现在解决了我的问题.它不是很漂亮,但它确实可以完成它的工作.

I solved my problem now. It is not beautiful, but it does what it is supposed to do.

Edit2:零钱

    int decide_dimension = data->nDataVar();
    std::vector<int> dimsOut;
    dimsOut.resize(3);
    dimsOut[0] = dims[0];
    dimsOut[1] = dims[1];
    dimsOut[2] = dims[2];
    if (decide_dimension != 1)
    {
        dimsOut.push_back(data->nDataVar());
    }

const size_t dataSize = data->primType().getTypeSize() * dimsOut[0] * dimsOut[1] * dimsOut[2] * ((decide_dimension == 1) ? 1 : dimsOut[3]);

推荐答案

您可以使用三元或条件运算符.基本形式是:

You can use the ternary or conditional operator. The basic form is:

condition ? valueIfTrue : valueIfFalse

示例:

const char* x = (SomeFunction() == 0) ? "is null" : "is not null";

SomeFunction()返回0时, x 用" is null "初始化,否则与"不为空".

When SomeFunction() returns 0, x is initialised with "is null", otherwise with "is not null".

这篇关于C ++根据条件初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆