有没有办法缩短这个if陈述的条件?
int x;
if (x != 3 && x != 8 && x != 87 && x != 9){
  SomeStuff();
}
我想的是这样的事情:
if (x != 3, 8, 87, 9) {}
但我试过了,它不起作用.我是否只需要将其全部写出来?
Ale*_*rru 43
如果您想知道整数是否在给定的整数集中,请使用std::set:
std::set<int> accept { 1, 4, 6, 8, 255, 42 };
int x = 1;
if (!accept.count(x))
{
    // ...
}
120*_*arm 32
为了完整起见,我将提供使用开关:
switch (x) {
    case 1:
    case 2:
    case 37:
    case 42:
        break;
    default:
        SomeStuff();
        break;
}
虽然这非常冗长,但它只评估x一次(如果它是一个表达式)并且可能生成任何解决方案的最有效代码.
Lin*_*gxi 29
这是我使用可变参数模板的解决方案.运行时性能与手动编写一样高效x != 3 && x != 8 && x != 87 && x != 9.
template <class T, class U>
bool not_equal(const T& t, const U& u) {
  return t != u;
}
template <class T, class U, class... Vs>
bool not_equal(const T& t, const U& u, const Vs&... vs) {
  return t != u && not_equal(t, vs...);
}
int main() {
  std::cout << not_equal( 3, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal( 8, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal(87, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal( 9, 3, 8, 87, 9) << std::endl;
  std::cout << not_equal(10, 3, 8, 87, 9) << std::endl;
}
Dar*_*ioP 14
那这个呢:
#include <iostream>
#include <initializer_list>
#include <algorithm>
template <typename T>
bool in(const T t, const std::initializer_list<T> & l) {
    return std::find(l.begin(), l.end(), t) != l.end();
}
int main() {
  std::cout << !in(3, {3, 8, 87, 9}) << std::endl;
  std::cout << !in(87, {3, 8, 87, 9}) << std::endl;
  std::cout << !in(10, {3, 8, 87, 9}) << std::endl;
}
或超载operator!=:
template<typename T>
bool operator!=(const T t, const std::vector<T> & l) {
    return std::find(l.begin(), l.end(), t) == l.end();
}
int main() {
  std::cout << ( 3!=std::vector<int>{ 3, 8, 87, 9}) << std::endl;
  std::cout << ( 8!=std::vector<int>{ 3, 8, 87, 9}) << std::endl;
  std::cout << (10!=std::vector<int>{ 3, 8, 87, 9}) << std::endl;
}
不幸的是,目前解析器不喜欢initializer_list作为运算符的参数,因此不可能std::vector<int>  在第二个解决方案中摆脱.
如果您不想一遍又一遍地重复此条件,请使用宏.
#include <iostream>
#define isTRUE(x, a, b, c, d)  ( x != a && x != b && x != c && x != d ) 
int main() 
{
    int x(2);
    std::cout << isTRUE(x,3,8,87,9) << std::endl;
    if ( isTRUE(x,3,8,87,9) ){
        // SomeStuff();
    }
    return 0;
}
如果数字不是“1,2,3,4”,而是随机整数的随机数,那么您可以将这些数字放入数据结构中(例如std::vector,然后使用循环(如下所示,std::find 是一个现成的选项)。
例如:
#include <algorithm>
int x;
std::vector<int> checknums;
// fill the vector with your numbers to check x against
if (std::find(checknums.begin(), checknums.end(), x) != checknums.end()){
    DoStuff();
}
| 归档时间: | 
 | 
| 查看次数: | 2302 次 | 
| 最近记录: |