检查是否存在于数组中的所有指标值 [英] check if value exists in all indexes of array

查看:130
本文介绍了检查是否存在于数组中的所有指标值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个字符数组(大小5),包含每个索引字符,我得到一个字符的用户输入数组中搜索。但我不知道如何检查字符cInput 是阵列的所有指标present。

So i have an array (size 5) of characters, each index containing a character, and i'm getting user input of a character to search for in the array. But i'm not sure how to check if char cInput is present in all indexes of the array.

char cLetters[5] = {'b', 'b', 'b', 'b', 'b'};
char cInput;
cout << "Enter a character to search for: ";
cin >> cInput;

我不应该这样做对吗?

I shouldn't have to do this right?

if(cInput == cLetters[0] && cInput == cLetters[1] && cInput == cLetters[2] 
&& cInput == cLetters[3] && cInput == cLetters[4])
          return true;

特别是如果数组的大小是200,我不会写条件的200倍。

Especially if the size of the array was 200, i wouldn't write that condition 200 times.

任何想法?

推荐答案

使用在C ++ 11的算法&LT;算法&GT; 的std :: all_of

Use the C++11 algorithm in <algorithm>, std::all_of.

举例code:

#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!";
    }
}

这篇关于检查是否存在于数组中的所有指标值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆