循环遍历向量的每个元素

dda*_*cot 3 c++

所以假设我有一个向量,它包含4个elemens [string elements].我需要首先遍历向量,然后遍历每个元素,循环遍历字符数组[元音]并计算该单词包含的元音数量.

    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)
       }
    }
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,我怎样才能遍历每个单词,我的意思b[i][j]是正确的方法呢?

如果是的话,这个表格会很好吗?:

if(b[i][j] == vowels[v]) {
//blabla
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

Owe*_* S. 5

更高级的方法,如果你认真学习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;
}
Run Code Online (Sandbox Code Playgroud)

你写的循环大致对应于这些行:

 std::transform(b.begin(), b.end(), counts.begin(), count_vowels);
 ..
 std::count_if(s.begin(), s.end(), is_vowel);
 ..
 std::find(vbegin, vend, s)
Run Code Online (Sandbox Code Playgroud)

这使用了高级功能/通用编程习惯用法,C++在推出IMO方面并不总是很优雅.但在这种情况下,它工作正常.

请参阅字符串中的元数字数,以了解我认为您要解决的部分问题的解决方案.您还可以看到各种可接受的循环/迭代技术.