簡體   English   中英

分配非零的第一個值(c ++)

[英]Assign first value that is not zero (c++)

在JavaScript中,您可以這樣寫:

var foo = value1 || value2. 

其結果是一個新的值value1 ,如果value1不是零和value2 ,如果value1為零。

在C ++中,此表達式的計算結果為truefalse

有沒有辦法在c ++中以某種方式模仿這種語法? (對於無限數量的值)。

auto foo = value1 ? value1 : value2;

沒有簡單的方法來擴展它。

您可以使用write一個接受任意數量參數的泛型函數:

#include <initializer_list>
#include <iostream>

int find_first(std::initializer_list<int> args) {
  for(int arg : args) {
    if (arg) {
      return arg;
    }
  }
  return -1;
}

int main(int argc, char** argv) {
  std::cout << find_first({0, 0, 1, 2}) << std::endl;
  std::cout << find_first({3}) << std::endl;
  std::cout << find_first({-1, -2, 0}) << std::endl;
  return 0;
}

這打印:

1
3
-1

您可以使用三元運算符

int i = (value1 != 0 ? value1 : value2)

這評估為

int i;

if (value1 != 0)
    i = value1;
else
    i = value2;

語法是

(condition ? trueOutput : falseOutput)

好的,我可以提出迄今為止jterrace解決方案的改進.. :)到目前為止它適用於可以從int分配的類型Foo。 這允許解決方案使用由多個類型的對象組成的列表,這些對象都可以與foo進行比較。

有什么我可以進一步改進,使這成為最通用的解決方案嗎?

    #include <initializer_list>
#include <iostream>
#include <stdio.h>

class Foo {
public:
    Foo(int v){val = v;}
    bool operator==(int v) const {return val == v;}
    bool operator!=(int v) const {return val != v;}
    operator int() const {return val;}
    int val; 
};

template<class Type>
Type find_first(std::initializer_list<Type> args) {
    auto it = args.begin(); 
    for(int c = 0; c < args.size(); c++) {
        if (*it != 0) {
            return *it;
        }
        if(c == args.size() - 1) return *it; 
        it++; 
    }
    // only get here if size == 0
    return Type(0);
}

int main(int argc, char** argv) {
    Foo *foo = new Foo(0);
    Foo bar = 0; 
    std::cout << find_first<Foo>({*foo, bar, 1}).val << std::endl;
    std::cout << find_first<int>({*foo, bar, (int)3.0f}) << std::endl; 
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM