c++ - 遍历 vector 的每个元素

标签 c++

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

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

关于c++ - 遍历 vector 的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246920/

相关文章:

c++ - QT : Templated Q_OBJECT class

java - JNI方法CallObjectMethod、CallObjectMethodV和CallObjectMethodA有什么区别?

c++ - 在 C++ 中使用 tinyxml2 读取 xml 文件

c++ - template specialization中的type会继续计算吗?

c++ - 动态库中的 libstdc++ 静态链接

c++ - 计算表达式的函数

c++ - 什么是非静态成员函数?

c++ - "C++filt"如何找到实际的类型名称?

c++ - R(macos 10.8.5),RcppArmadillo : can not find armadillo library or symbol _wrapper_ddot_

c++ - 另外重载的代码没有效果