如果你想认真学习C ++,一种更高级的方法是不使用索引和随机访问,而是使用高级STL函数。考虑以下内容:
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>
bool is_vowel(char s) {
static const char vowels[] = { 'a', 'e', 'i', 'o', 'u' };
const char* vbegin = vowels;
const char* vend = vowels + sizeof(vowels)/sizeof(char);
return (std::find(vbegin, vend, s) != vend);
}
std::string::difference_type count_vowels(const std::string& s) {
return std::count_if(s.begin(), s.end(), is_vowel);
}
template <class T> void printval(const T& obj) { std::cout << obj << std::endl; }
int main() {
std::vector<std::string> b;
b.push_back("test");
b.push_back("aeolian");
b.push_back("Mxyzptlk");
std::vector<int> counts(b.size());
std::transform(b.begin(), b.end(), counts.begin(), count_vowels);
std::for_each(counts.begin(), counts.end(), printval<int>);
int total = std::accumulate(counts.begin(), counts.end(), 0);
printval(total);
return 0;
}
您编写的循环大致相当于这些行:
std::transform(b.begin(), b.end(), counts.begin(), count_vowels);
..
std::count_if(s.begin(), s.end(), is_vowel);
..
std::find(vbegin, vend, s)
这里采用了一种高级函数式/泛型编程方法,我认为C++并不总是能够优雅地实现它。但在这种情况下,它可以很好地工作。
请参见计算字符串中元音字母数量,其中列出了我认为您正在尝试解决的问题的一些解决方案。你也可以看到各种可接受的循环/迭代技巧。