标签: conditional-operator

条件运算符和比较委托

给出了两种比较方法的实现:

// compares by Key...
private static int CompareByKey(KeyValuePair<int, string> x, KeyValuePair<int, string> y)

{
    return x.Key.CompareTo(y.Key);
}

// compares by Value...
private static int CompareByValue(KeyValuePair<int, string> x, KeyValuePair<int, string> y)
{
    return x.Value.CompareTo(y.Value);
}
Run Code Online (Sandbox Code Playgroud)

为什么下面的条件运算符代码块不能编译:

Comparison<KeyValuePair<int, string>> sortMethod;
sortMethod = isSortByActualValue ? CompareByKey : CompareByValue;
Run Code Online (Sandbox Code Playgroud)

编译器错误:"无法确定条件表达式的类型,因为'方法组'和'方法组'之间没有隐式转换"

但是,使用if-else的等效代码块没有任何问题:

Comparison<KeyValuePair<int, string>> sortMethod;
if (isSortByActualValue)
    sortMethod = CompareByKey;
else
    sortMethod = CompareByValue;
Run Code Online (Sandbox Code Playgroud)

(以上两项任务都很好)

如果我转换了比较委托,则条件运算符也是如此:

Comparison<KeyValuePair<int, string>> sortMethod;
sortMethod = isSortByActualValue ? (Comparison<KeyValuePair<int, string>>) CompareByKey : CompareByValue;
Run Code Online (Sandbox Code Playgroud)

(在上面的任务中都很好,即使施法只是在真正的部分时施放)

.net c# ternary-operator conditional-operator visual-studio

5
推荐指数
1
解决办法
559
查看次数

三元运算符和赋值运算符

C/C++ 三元运算符实际上与赋值运算符具有相同的优先级吗

Luchian Grigore 的回答说,类似的情况

a ? b : c = d
Run Code Online (Sandbox Code Playgroud)

总是会被推断为

a ? b : ( c = d )
Run Code Online (Sandbox Code Playgroud)

因为 = 和 ?: 从右到左关联,所以

在 C++ 中

k =  21 > 3 ? j = 12 : j = 10;
Run Code Online (Sandbox Code Playgroud)

k = 1 > 3 ? j = 12 : j = 10;
Run Code Online (Sandbox Code Playgroud)

两者都很好。

在C中

k = 21 > 3 ? 12 : j = 10
Run Code Online (Sandbox Code Playgroud)

返回错误

invalid lvalue in assignment.
Run Code Online (Sandbox Code Playgroud)

上面不应该被推断为(并且不返回错误)

k=  21 > …
Run Code Online (Sandbox Code Playgroud)

c c++ conditional-operator associativity assignment-operator

5
推荐指数
1
解决办法
7105
查看次数

没有可用的用户定义转换运算符可以执行此转换,或者无法调用该运算符

我有一个奇怪的错误,我不太明白,VS2013。这只是我的实际问题的简化,导致了同样的错误。

std::function<bool()> x = (someCondition == true)
    ? []() { return true; }
    : []() { return false; };
Run Code Online (Sandbox Code Playgroud)

VS 编译器错误是:

1>f:\test\cppconsoleapplication\cppconsoleapplication.cpp(497): error C2446: ':' : no conversion from 'main::<lambda_96d01fe3721e46e4e8217a69a07d151b>' to 'main::<lambda_0d38919a9b2aba5caf910d83eac11776>'
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Run Code Online (Sandbox Code Playgroud)

IntelliSense 甚至想出了这个神秘的错误消息:

IntelliSense: more than one operator "?" matches these operands:
        built-in operator "expression ? pointer : pointer"
        built-in operator "expression ? pointer : pointer"
        built-in operator "expression ? pointer : pointer" …
Run Code Online (Sandbox Code Playgroud)

c++ lambda conditional-operator std-function

5
推荐指数
1
解决办法
4064
查看次数

打字稿 2 - 在三元/条件运算符表达式中抛出

我尝试编译:

const value = "20"
const x : string | never = "10" === value ? throw Error("bad things") : "hello"
Run Code Online (Sandbox Code Playgroud)

...并在throw- 上出错expression expected。我可以使用就地调用的内联方法解决这个问题,但这看起来不太好。( (() => {throw Error("bad things"})())

为什么不能放入三元运算符的分支?或者是否有另一种有效的语法,也许是我缺少的编译选项?

在变通方法 ( (() => throw Error("bad things")()) 中,如果函数体中没有大括号,Throw 似乎也不起作用。

exception conditional-operator typescript

5
推荐指数
3
解决办法
3469
查看次数

python 是否有速记来检查对象是否具有属性?

背景是我从 JSON API 获取数据,其中许多字段是可选的,我想要数据库中的大部分字段。当特定字段不可用时,我希望将空字符串 ( "") 写入数据库。

目前我一直在做:

if jsonobject.what_i_look_for:
  dbstring = jsonobject.what_i_look_for
else:
  dbstring = ""
Run Code Online (Sandbox Code Playgroud)

然后将dbstring插入到数据库中。然而,我现在得到了更多这些字段,我想要一个更清晰的代码,而不是一个包含大约 80% 的 if 语句的函数。

我找到了if-shorthandsthis shorthand 来检查变量是否为空,但两者似乎都不能直接作为字符串工作。我已经print()在交互式 python 3.5.2 shell 中对此进行了测试:

>>> print(testvar or "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined

>>> print(testvar if testvar else "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'testvar' is not defined
Run Code Online (Sandbox Code Playgroud)

这: …

python string if-statement conditional-operator python-3.x

5
推荐指数
1
解决办法
7916
查看次数

Angular:在 html 模板中使用三元运算符

简单的三元运算符可以在 html 中像这样使用:

<div> {{ showStringOneFlag ? 'Display String 1' : 'Display String 2' }} </div>
Run Code Online (Sandbox Code Playgroud)

这可能比在 javascript 中设置一个字符串变量 20 次更方便。

我的问题是三元运算符是否太昂贵而无法在每个摘要周期执行?是否应该避免或少用此功能?它在消化循环中的足迹是否很小并且无需担心?我在任何地方寻找答案时都发现它在速度方面与 if/else 语句相当,但在 html 中并没有真正与 if/else 语句等效的东西。

html conditional-operator angular

5
推荐指数
1
解决办法
2万
查看次数

试图避免在 for 循环中使用 if-else 语句,但代码似乎有一些错误

这个片段工作得很好。

for (int i = 0; i < 1; i++) // for some other purpose
{
  // some other code

  double** angle = new double* [10];   // for a 2D matrix
  for (int j = 0; j < 10; j++)
  {
     angle[j] = new double [3];

     if (j == 0) 
            angle[j][0] = 2;          // focused on the first column for now
     else 
            angle[j][0] = angle[j-1][0]+3;

     std::cout << angle[j][0] << std::endl;
  }

  for (int i = 0; i < 10; i++) …
Run Code Online (Sandbox Code Playgroud)

c++ for-loop conditional-operator

5
推荐指数
1
解决办法
169
查看次数

C++11 auto 和 decltype

当阅读有关 auto 和 decltype (C++11) 的内容时,我看到以下函数

auto findMin(A a, B b) -> decltype(a < b ? a : b)
{
    return (a < b) ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

这部分 -> decltype(a < b ? a : b) 对我来说很奇怪。什么样的函数声明或者它只适用于 auto 和 decltype ?

c++ conditional-operator decltype auto c++11

5
推荐指数
1
解决办法
892
查看次数

使用字符串文字作为使用三元运算符的表达式的结果是否有效/建议?

以下代码在 C 语言中有效/良好实践吗?

int x = 1;
printf(x == 1 ? "%d second elapsed" : "%d seconds elapsed", x);
Run Code Online (Sandbox Code Playgroud)

它编译得很好,所以我认为它很好(也因为它只是 if-else 块的语法糖),但如果有人有一些额外的见解,我将不胜感激,谢谢。

PS,我想 C++ 也是如此?

c conditional-operator string-literals

5
推荐指数
1
解决办法
121
查看次数

将 std::move shared_ptr 与条件运算符一起使用时的奇怪行为

我正在使用std::moveon编写一些 C++ 代码shared_ptr,并得到了非常奇怪的输出。我简化了我的代码如下

int func(std::shared_ptr<int>&& a) {
    return 0;
}

int main() {
    std::shared_ptr<int> ptr = std::make_shared<int>(1);

    for (int i = 0; i != 10; ++i) {
        func(i == 9 ? std::move(ptr) : std::shared_ptr<int>(ptr));
    }

    if (ptr) {
        std::cout << "ptr is not null: " << *ptr << "\n";
    } else {
        std::cout << "ptr is null\n";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到了输出

ptr is null
Run Code Online (Sandbox Code Playgroud)

正如我所预期的,我的ptrwill 在最后一个循环中被移动(转换为std::shared_ptr<int>&&),并且由于func从不窃取 中的内存a,所以我的 …

c++ conditional-operator shared-ptr move-constructor move-semantics

5
推荐指数
1
解决办法
153
查看次数