边做边循环多条件评估C++
do-while loop multiple condition evaluation C++
这学期有一个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_of
和std::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 比较这个(向量(,这个(数组(和那个。
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- c++11评估顺序(未定义的行为)
- 如何使用"equal to"以外的评估编写开关语句
- 嵌套 if 中没有返回评估
- 懒惰的参数评估try_emplace?
- 在实践中,在运行时为零的乘法中是否有任何"lazy"评估
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- C++17:使用 std::optional 来评估枚举是否包含值
- CNTK:->转发或 ->评估某些电脑上的崩溃,而不是其他电脑上的崩溃
- ConstexPR :GCC比Clang更努力地评估ConstexPR
- C++:Constexpr斐波那契数列评估
- C++能保证论点评估的原子性吗?
- 在编译时评估函数开销的通用方法
- 如何使用 std::forward 精确地评估参数包的扩展?
- MSVC 在不知道类型的情况下评估上下文(和错误)
- C++评估顺序优化是否意味着对不同的操作数使用不同的内核?
- 条件分支评估
- C++ constexpr语言 - 可以在编译时评估值吗?
- 井字游戏:评估节点的启发式值
- 布尔值始终评估为真