繁体   English   中英

比较未知数量的变量的宏C ++

[英]Macro that compares an unknown number of variables C++

我正在尝试建立一个将比较用户指定数量的变量的宏,如下所示:

#include <iostream>

//compares x to only a and b
#define equalTo(x, a, b) x != a && x != b 

int main()
{
    int x;

    do
    {
        std::cout << "x = ";
        std::cin >> x;
    } while (equalTo(x, 1, 2));  //I wanna input as many as i want to be compared to "x"
    //for example i want equalTo(x, 1, 2, 3, 4, 5) to work too, without a new macro

    std::cout << "x = " << x;

    std::cin.ignore();
    std::cin.get();
    return 0;
}

我有点卡住,不知道该去哪里。

我不会对宏执行此操作,但是可变参数模板提供了一种解决方案:

#include <ctime>
#include <cstdlib>
#include <iostream>

template<typename X, typename Arg>
bool notEqualTo(X x, Arg arg)
{
    return x != arg;
}

template<typename X, typename Arg, typename... Args>
bool notEqualTo(X x, Arg arg, Args... args)
{
    return notEqualTo(x, arg) && notEqualTo(x, args...);
}

int main()
{
    std::srand(std::time(0));

    for(int i = 0; i < 10; ++i)
    {
        int x = std::rand() % 10;
        int a = std::rand() % 10;
        int b = std::rand() % 10;
        int c = std::rand() % 10;

        std::cout << x << ": (" << a << ", " << b << ", " << c << ") ";
        std::cout << std::boolalpha << notEqualTo(x, a, b, c) << '\n';
    }
}

输出:

5: (9, 8, 0) true
7: (4, 3, 4) true
1: (3, 2, 5) true
7: (4, 7, 0) false
8: (9, 9, 8) false
5: (8, 4, 4) true
9: (9, 9, 4) false
8: (8, 6, 3) false
7: (4, 5, 4) true
0: (1, 0, 4) false
template <typename T>
bool all_not_equal(T a, const vector<T>& others) {
    for (auto& other : others) {
        if (a == other) {
            return false;
        }
    }

    return true;
}

在这种情况下,请尽量避免使用宏。 同时命名您的函数以反映您的逻辑。 equalTo表示如果所有均等于a则返回true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM