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

时间:2015-08-13 02:46:56

标签: 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;
}

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

2 个答案:

答案 0 :(得分:4)

我不会用宏来做这件事,但可变参数模板提供了解决方案:

#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

答案 1 :(得分:2)

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