将多个值与同一变量进行比较时'!='运算符最简洁的方法是什么?
What is the most succinct way to use '!=' operator when comparing multiple values to the same variable?
编辑:我并不是说效率在程序中更有效地运行效率,但我的意思是是对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::vector
或std::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
,这是相当简洁的,并且与!=
语法匹配。请注意,您的开发人员可能不喜欢这种情况,因为与"正常"方式(您想避免的)相比,这将是一种不寻常的成语。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 将多个值与同一变量进行比较时'!='运算符最简洁的方法是什么?
- 如何使 g++ 运算符重载错误更简洁