【问题标题】:return cur == NULL ? -1 : cur->val; (I am confused for this c++ sentence) [duplicate]返回 cur == NULL ? -1:cur->val; (我对这个 c++ 句子感到困惑)[重复]
【发布时间】:2019-02-07 11:23:43
【问题描述】:
    /** Helper function to return the index-th node in the linked list. */
SinglyListNode* getNode(int index) {
    SinglyListNode *cur = head;
    for (int i = 0; i < index && cur; ++i) {
        cur = cur->next;
    }
    return cur;
}
/** Helper function to return the last node in the linked list. */
SinglyListNode* getTail() {
    SinglyListNode *cur = head;
    while (cur && cur->next) {
        cur = cur->next;
    }
    return cur;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
    SinglyListNode *cur = getNode(index);
    return cur == NULL ? -1 : cur->val;
}

这个“返回 cur == NULL ? -1:cur->val; ”

我把这个语法弄糊涂了,有人能把这句话分开吗?

【问题讨论】:

标签: c++


【解决方案1】:

这是ternary operator。也称为条件运算符。

这用作单行条件语句。

这相当于:

if (cur == NULL)
{
    return -1;
}
else
{
    return cur->pos;
}

更多信息请参考以上链接。

【讨论】:

  • 它是 a 三元运算符,但更具体地说是 the 条件运算符。并且请不要发布链接到自我声明过时的网页。
  • SinglyListNode* getNode(int index) { SinglyListNode *cur = head; for (int i = 0; i
  • @YuxiaoZheng • 指针隐式转换为布尔值。如果指针为 nullptr,则转换为 false,否则转换为 true。看起来您可以使用一本不错的 C++ 入门书籍,这里是精选的 C++ 书籍精选列表:stackoverflow.com/questions/388242/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 2021-04-06
相关资源
最近更新 更多