边做边循环多条件评估C++

do-while loop multiple condition evaluation C++

本文关键字:评估 C++ 条件 循环      更新时间:2023-10-16

这学期有一个C++课。上个学期我们正在学习Python,现在做一个作业,我需要做一个do-while循环,当变量不等于数组中的多个数字之一时循环。在python中,我会使用"not in"函数,例如:

if a not in (1,2,3,4):

或类似的东西。我天真的尝试在C++做同样的事情是这样的:

do {...}while(userin != (1,2,3,4);

但显然它不起作用。

有谁知道如何在C++做到这一点?

您可以使用标准库函数从算法标头中查找。例如:

int user = // this comes from your code...;
std::vector<int> exclude{1,2,3,4};
do {...} while (std::find(exclude.begin(), exclude.end(), user) == exclude.end());

这将在用户不在排除数组中时循环。

但是你必须小心你在循环中改变的内容和方式:用户和/或排除 ->否则你很容易得到一个无限循环。您必须确保终止条件,也许还有一些额外的计数器等。

您还可以创建自己的模板化函数,用于在某些容器中搜索值,例如:

template<typename Container, typename T>
bool within(const Container& c, T value) {
    return std::find(std::begin(c), std::end(c), value) != std::end(c);
}

然后你可以这样称呼它:

do {...} while !within(exclude, user);

其他例子:

std::vector<int> v{1,2,3};
std::cout << boolalpha 
    << within(v, 1) << std::endl
     << within(v, 5) << std::endl;
std::string s = "Hello world";
std::cout << within(s, 'o') << std::endl
          << within(s, 'x') << std::endl;

这里有活的例子:https://wandbox.org/permlink/qEzDZ93HvCaU0bJb

没有其他答案指出<algorithm>中有一个标准函数的事实。

#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> a = { 1,2,3,4,5 };
    if (std::any_of(a.begin(), a.end(), [](int val){ return val == 3; })) // true
        std::cout << "3 is in a" << std::endl;
    if (std::any_of(a.begin(), a.end(), [](int val){ return val == 7; })) // false
        std::cout << "7 is in a" << std::endl;
    return 0;
}

同样,也有std::all_ofstd::none_of.

假设数组是排序的,你可以使用bsearch,或者你需要实现搜索逻辑,就像alrtold 所说的那样。

C++ 中没有对此的内置支持,因此您必须自己实现它。这是一种方法。

int bar;
std::vector<int> arr{1, 2, 3, 4};
do {
   // Code
} while (std::find(arr.begin(), arr.end(), bar) == arr.end());

您可以将std::vector<int>更改为std::array<int, 4>.缺点是您必须指定大小,但它比 vector .

即使临时std::vector中的std::find可能会被编译器优化掉(它肯定不会1(,但一种有保证的有效方法是"手动"比较:

do {...} while (userin != 1 && userin != 2 && userin != 3 && userin != 4);

在您的特定示例中,如果userin是整数类型,则可以:

do {...} while (userin < 1 || userin > 4);

1 比较这个(向量(,这个(数组(和那个。