循环遍历向量的每个元素

时间:2012-02-12 06:24:10

标签: 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)
       }
    }

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

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

if(b[i][j] == vowels[v]) {
//blabla
}

感谢。

2 个答案:

答案 0 :(得分: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;
}

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

 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,了解我认为您正试图解决的部分问题的解决方案。您可以在那里看到各种可接受的循环/迭代技术。

答案 1 :(得分:2)

std::vector<T>定义T operator[](int)。这意味着您可以通过x访问向量i的元素x[i]

std::string定义char operator[](int),它会在字符串中的该位置返回char

因此,如果您有一个名为std::vector<std::string>的{​​{1}},x将返回该向量的x[i][j]位置中字符串的j个字符

这不是惯用的C ++方法 - 最常见的方法是迭代器(i.begin()调用)。但由于向量访问是恒定时间(就像字符串字符访问一样),因此并不是一件大事。