2013-12-15 2 views
3

그래서 배열의 문자 (크기 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 번 기록하지 않습니다.

아이디어가 있으십니까?

+0

질문에 대한 답변 - 루프. 그 아이디어에 대해 어때요? – ApproachingDarknessFish

+0

나는 하루 종일 두뇌를 내팽개 쳤다. 내 사과 – Mauri

답변

10

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

+1 허, 나는 'all_of'가 존재한다는 것을 몰랐다. –

+0

@ Cheersandhth.-Alf, 알 수없는 것처럼 보이는 C++ 11에 추가 된 유용한 알고리즘과 유틸리티가 실제로 얼마나 놀라운 것입니까? 'std :: to_string'과'std :: stoi'는 나이를 먹었습니다. – chris

0

입력 문자는 모든 인덱스에 존재하지 않는다. 배열을 통해 루프

for (int i=0; i<5; ++i){ 
    if (cInput != cLetters[i]) 
     return 0; 
} 
return 1; 
0

은 또 다른 가능성은 사용하는 것입니다 볼 수있는 C++ (11) 루프가 약간의 코드를 단순화하는 범위 기반 :

for (auto ch : cLetters) 
    if (ch != cInput) 
     return false; 
return true; 
2

내가 찾고 있어요를 방법은 bools이 작업을 수행하고이 함께했다합니다 : 그렇게 같을 것이다 CHAR const를 통한

auto is_true = std::bind(std::equal_to<bool>(), std::placeholders::_1, true); 
return std::all_of(v.begin(), v.end(), is_true) 

:

auto is_b = std::bind(std::equal_to<char>(), std::placeholders::_1, 'b'); 
return std::all_of(v.begin(), v.end(), is_b) 
관련 문제