检查数组的所有索引中是否存在值
check if value exists in all indexes of array
所以我有一个字符数组(大小为5),每个索引都包含一个字符,并且我得到用户输入的要在数组中搜索的字符。但我不知道如何检查char cInput
是否存在于数组的所有索引中。
char cLetters[5] = {'b', 'b', 'b', 'b', 'b'};
char cInput;
cout << "Enter a character to search for: ";
cin >> cInput;
我不应该这么做,对吧?
if(cInput == cLetters[0] && cInput == cLetters[1] && cInput == cLetters[2]
&& cInput == cLetters[3] && cInput == cLetters[4])
return true;
特别是如果数组的大小是200,我不会写200次这个条件。
有什么想法吗?
在<algorithm>
、std::all_of
中使用C++11算法。
示例代码:
#include <algorithm>
#include <iostream>
int main() {
char x[] = { 'b', 'b', 'b', 'b', 'b' };
if(std::all_of(std::begin(x), std::end(x), [](char c) { return c == 'b'; })) {
std::cout << "all are b!";
}
}
我正在寻找一种用bools实现这一点的方法,并想出了这个:
auto is_true = std::bind(std::equal_to<bool>(), std::placeholders::_1, true);
return std::all_of(v.begin(), v.end(), is_true)
如果使用const字符,它看起来是这样的:
auto is_b = std::bind(std::equal_to<char>(), std::placeholders::_1, 'b');
return std::all_of(v.begin(), v.end(), is_b)
如果输入字符在其中任何一个索引中都不存在,则它不会出现在所有索引中。在阵列中循环查看
for (int i=0; i<5; ++i){
if (cInput != cLetters[i])
return 0;
}
return 1;
另一种可能性是使用基于C++11范围的for循环来稍微简化代码:
for (auto ch : cLetters)
if (ch != cInput)
return false;
return true;
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 地图计数确实很重要,或者只是检查是否存在
- C++中是否存在 std::conditional 的懒惰等价物?
- 无论如何,我可以确定构造函数是否存在吗?
- COM :是否可以查看是否存在对我的某个 COM 对象的进程外引用?我可以释放它吗?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 扩展类中的可选 vir 函数,测试它在运行时是否存在
- 模板化检查是否存在带有参数列表的类成员函数?
- 是否存在包含负号的isdigit函数(过载)
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 检查编译时是否存在静态函数
- 向量是否存在行主要形式?
- 检查 TinyXML 中的元素是否存在
- 检测是否存在具有 C++17 的类成员
- 虚拟继承中是否存在多重继承?
- 我遇到了这个代码片段,不明白. 它递归检查 C++ 字符串中是否存在大写字符
- std::weak_ptr 和相应的 std::shared_ptr 之间是否存在数据竞争?
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?