假设我有一个 vector ,其中包含4个元素[string elements]。我需要先遍历 vector ,然后遍历每个元素,遍历字符数组[元音]
并计算该单词包含多少个元音。

    for(int i = 0; i < b.size(); i++)
    {
      for(int j = 0; j < b[i].size(); j++)
       {
         for(int v = 0 ; v < sizeof( vowels ) / sizeof( vowels[0] ); v++)
          if(//blabla)
       }
    }

所以我的问题是,我该如何遍历每个单词,我的意思是b[i][j]是做到这一点的正确方法?

如果是的话,这种形式会很好吗? :
if(b[i][j] == vowels[v]) {
//blabla
}

谢谢。

最佳答案

一种更高级的解决方法,如果您认真学习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++在推出IMO时并不总是很优雅。但是在这种情况下,它可以正常工作。

有关我认为您要解决的部分问题的解决方案,请参阅Count no of vowels in a string。您还可以在那里看到各种可接受的循环/迭代技术。

09-09 23:46
查看更多