2010-10-30 295 views
4

如何使用find函數查找char數組中的char?如果我只是爲了循環元音,那麼我可以得到答案,但我被要求使用std :: find ..謝謝。C++如何使用find函數查找char數組中的char?

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; 
} 

回答

4
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); 
} 
+0

太棒了。很酷..非常感謝... – 2010-10-30 19:16:36

2

std::find(first, last, value)返回一個迭代器,其在範圍匹配value的第一個元素[第一,最後一個)。如果沒有匹配,則返回last

特別是,std :: find不返回布爾值。爲了獲得你正在尋找的布爾值,你需要比較std :: find的返回值(沒有將它轉換爲布爾值!)到last(即,如果它們相等,則不匹配)。

+0

我必須使用char :: iterator嗎?我認爲沒有像char:iterator這樣的東西,對吧?我應該使用什麼樣的迭代器?以及如何檢查它是否結束?通常,如果它是一個字符串,我們可以像s.end()==那樣做,但數組不會有.end()。 – 2010-10-30 19:14:51

+0

char *(指向char的指針)在這種情況下是一個迭代器。你的例子中的'end'是'元音+ 5'。當然,使用std :: vector或std :: string會更容易一些(或者較不復雜)。 – 2010-10-30 19:17:48

+0

謝謝,eq- ..。 – 2010-10-30 19:28:44