tags:

views:

41

answers:

3

Hello,

How to find char in a char array by using find function? If I just for loop the vowel then I could have gotten the answer but I'm asked to use std::find.. Thanks.

bool IsVowel (char c) { 

    char vowel[] = {'a', 'e', 'i', 'o', 'u'};            
    bool rtn = std::find(vowel, vowel + 5, c);

    std::cout << " Trace : " << c  << " " << rtn << endl;

    return rtn; 
 }
+2  A: 

std::find(first, last, value) returns an iterator to the first element which matches value in range [first, last). If there's no match, it returns last.

In particular, std::find does not return a boolean. To get the boolean you're looking for, you need to compare the return value (without converting it to a boolean first!) of std::find to last (i.e. if they are equal, no match was found).

eq-
Do I have to use char::iterator? I think there is no such things as char:iterator, right? What kind of iterator should I use? And how to check whether it's end or not? Normally, if it's a string, we can do like s.end() == it but array doens't have .end().
Michael Sync
char* (pointer to char) is an iterator in this context. Your `end` in your example is `vowel+5`. It would, of course, be somewhat easier (or less complex) to use std::vector or std::string.
eq-
Thanks, eq-.. .
Michael Sync
A: 

Use:

size_t find_first_of ( char c, size_t pos = 0 ) const;

Reference: http://www.cplusplus.com/reference/string/string/find_first_of/

Yasky
+2  A: 
bool IsVowel (char c) { 

    char vowel[] = {'a', 'e', 'i', 'o', 'u'};
    char* end = vowel + sizeof(vowel) / sizeof(vowel[0]);            
    char* position = std::find(vowel, end, c);

    return (position != end); 
 }
Maciej Hehl
great. cool.. Thanks a lot...
Michael Sync