将多个值与同一变量进行比较时'!='运算符最简洁的方法是什么?

What is the most succinct way to use '!=' operator when comparing multiple values to the same variable?

本文关键字:运算符 简洁 是什么 方法 比较 变量      更新时间:2023-10-16

编辑:我并不是说效率在程序中更有效地运行效率,但我的意思是是对IF语句进行编程的更快方法。

我正在尝试找到一种方法来降低我的代码以提高效率。例如: if(x!=10 && x!=20 && x!=30){}//etc`

我尝试了一下,然后尝试了多种其他方法:

if(x!=(10 && 20 && 30){}

它不起作用。有没有办法减少此IF此语句的大小?

一种方法是使用 switch

switch (x)
{
    case 10:
    case 20:
    case 30:
        break;
    default:
        // do something ...
        break;
}

另一种方法是使用数组(或等效的STL容器,例如std::vectorstd::array):

#include <algorithm>
const int okValues[] = {10, 20, 30};
const int *end = &okValues[3];
if (std::find(okValues, end, x) == end)
{
    // do something ...
}

#include <vector>
#include <algorithm>
std::vector<int> okValues;
okValues.push_back(10);
okValues.push_back(20);
okValues.push_back(30);
/* or, in C++11 and later:
std::vector<int> okValues {10, 20, 30};
*/
if (std::find(okValues.begin(), okValues.end(), x) == okValues.end())
{
    // do something ...
}

// C++11 and later only...
#include <array>
#include <algorithm>
std::array<int, 3> okValues = {10, 20, 30};
if (std::find(okValues.cbegin(), okValues.cend(), x) == okValues.cend())
{
    // do something ...
}

另一种方法是使用std::set

#include <set>
const int arr[] = {10, 20, 30};
const std::set<int> okValues(arr, arr+3);
/* or, in C++11 and later:
const std::set<int> okValues {10, 20, 30};
*/
if (okValues.find(x) == okValues.end()) // or cend() in C++11 and later
{
    // do something ...
}

或在您特定特定的3个示例值的非常具体的情况下:

int result = x / 10;
int remainder = x % 10;
if ((result < 1) || (result > 3) || (remainder != 0))
{
    // do something...
}

有没有办法减少此IF语句的大小?...并不像计划中的效率更有效地运行,而是...编程if语句。

更快的方法。

我将这意味着您想要的字符比if (x!=10 && x!=20 && x!=30)和/或"更容易"的键入而不是代码更快。

一种方式,类似于Remy的答案,使用set。使用公用程序例程,例如:

bool in(int x, const std::initializer_list<int>& values)
{
    const std::set<int> s{ values };
    return s.find(x) != s.cend();
}

您的if语句现在为if (!in(x, { 10, 20, 30 }))。(几乎没有)减少了整体字符数,并且与!=&&的输入可能稍微容易多次。

而不是in()功能,您可以超载!=这样的操作员:

bool operator !=(int x, const std::set<int>& s) {
    return s.find(x) == s.cend();
}

然后使用它

using si = std::set<int>; // si == set<int>
if (x != si{ 10, 20, 30 } ) { }

忽略using,这是相当简洁的,并且与!=语法匹配。请注意,您的开发人员可能不喜欢这种情况,因为与"正常"方式(您想避免的)相比,这将是一种不寻常的成语。