[英]Assign first value that is not zero (c++)
在JavaScript中,您可以这样写:
var foo = value1 || value2.
其结果是一个新的值value1
,如果value1
不是零和value2
,如果value1
为零。
在C ++中,此表达式的计算结果为true
或false
。
有没有办法在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.