对不起,这个问题..。我想要user ternar操作符for和if else语句。我想问一下,是否需要像示例2那样使用方括号,或者示例1可以吗?我知道两者都编译..。谢谢。
#include <iostream>
using namespace std;
int main()
{
int x2;
if (x == 14)
{
x2 = 10;
}
else if (x == 14)
{
x2 = 140;
}
else
{
x2 = 0;
}
int x = 14;
// example1
auto x2 = x == 10 ? 100 : x == 14 ? 140 : 0;
// example2
auto x2 = x == 10 ? (100 : x == 14 ? 140 : 0);
return 0;
}发布于 2021-08-27 09:36:09
加上括号只是为了增加三元操作符的清晰度。如果将代码放在正确的位置,则不应影响代码流。
这里没有方括号,其含义仍然与以下所示相同:
x2 = x == 10 ? 100 : x == 14 ? 140 : 0;在这里,我尽可能多地放括号。
x2 = (x == 10) ? (100) : ((x == 14) ? (140) : (0));虽然这些括号对用户来说是清晰的,但过度使用它们可能会使阅读变得复杂,我的看法是按以下方式编写它
x2 = (x == 10) ? 100 : ((x == 14) ? 140 : 0);所有这些都意味着
if (x == 10) {
x2 = 100;
} else {
if (x == 14){
x2 = 140;
} else {
x2 = 0;
}
}发布于 2021-08-27 10:02:05
当您需要更多的比较时,您可以这样做(我为自己做了一个节选,所以不是真正的答案):
#include <cassert>
#include <map>
template<typename type_t, unsigned int N>
constexpr type_t n_ary(const type_t& value, const type_t& default_value, const std::pair<type_t, type_t>(&options)[N])
{
for (const auto& option : options)
{
if (value == option.first) return option.second;
}
return default_value;
}
int main()
{
auto x= 8;
// x = is your value
// 0 = default value if nothing matches
// per pair, first is the value to match, second is value to return
auto x2 = n_ary(x, 0, {{ 10,100 }, {14,140}, {8,42}, {6,36}});
assert(x2==42);
}https://stackoverflow.com/questions/68951014
复制相似问题