[英]Assign first value that is not zero (c++)
In JavaScript you can write this: 在JavaScript中,您可以这样写:
var foo = value1 || value2.
The result is a new value that is value1
if value1
is not zero and value2
if value1
is zero. 其结果是一个新的值value1
,如果value1
不是零和value2
,如果value1
为零。
In C++ this expression is evaluated to true
or false
instead. 在C ++中,此表达式的计算结果为true
或false
。
Is there a way to imitate this syntax somehow in c++? 有没有办法在c ++中以某种方式模仿这种语法? (for unlimited number of values). (对于无限数量的值)。
auto foo = value1 ? value1 : value2;
没有简单的方法来扩展它。
You could use write a generic function that would accept any number of arguments: 您可以使用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;
}
This prints: 这打印:
1
3
-1
You could use the ternary operator 您可以使用三元运算符
int i = (value1 != 0 ? value1 : value2)
This evaluates to 这评估为
int i;
if (value1 != 0)
i = value1;
else
i = value2;
And the syntax is 语法是
(condition ? trueOutput : falseOutput)
Ok so best I could come up with so far is an improvement of the jterrace solution.. :) So far it works with a type Foo that can be assigned from int. 好的,我可以提出迄今为止jterrace解决方案的改进.. :)到目前为止它适用于可以从int分配的类型Foo。 This allows the solution to work with a list that consists of objects of multiple types that can all be compared to foo. 这允许解决方案使用由多个类型的对象组成的列表,这些对象都可以与foo进行比较。
Is there anything I can improve further to make this the most generic solution possible? 有什么我可以进一步改进,使这成为最通用的解决方案吗?
#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.