c – 循环遍历向量的每个元素
发布时间:2020-12-16 09:40:25 所属栏目:百科 来源:网络整理
导读:所以假设我有一个向量,它包含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(
所以假设我有一个向量,它包含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 } 谢谢. 解决方法
一个更高级的方法,如果你认真学习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(),0); printval(total); return 0; } 你写的循环大致对应于这些行: std::transform(b.begin(),count_vowels); .. std::count_if(s.begin(),is_vowel); .. std::find(vbegin,s) 这使用了一种高级功能/通用编程习惯用法,C在拉出IMO时并不总是很优雅.但在这种情况下,它工作正常. 请参阅Count no of vowels in a string,了解我认为您正试图解决的部分问题的解决方案.您还可以看到各种可接受的循环/迭代技术. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |