so let's say i have a vector, wich contains 4 elemens [string elements]. I need to loop through the vector first , then through each element , loop through an array of chars [vowels] and to count how many vowels does that word contain.
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)
}
}
so my question is, how can i loop through each word , i mean b[i][j] is the right way to do that?
if yes, this form , will work great? :
if(b[i][j] == vowels[v]) {
//blabla
}
thanks.
A more advanced way to go about this, which you should take a look at if you're serious about learning C++: don't use indices and random access, use high-level STL functions. Consider:
#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;
}
Where the loops you've written correspond roughly to these lines:
std::transform(b.begin(), b.end(), counts.begin(), count_vowels);
..
std::count_if(s.begin(), s.end(), is_vowel);
..
std::find(vbegin, vend, s)
This uses a high-level functional/generic programming idiom that C++ is not always elegant at pulling off IMO. But in this case it works fine.
See Count no of vowels in a string for a rundown of solutions to part of the problem I think you're trying to solve. You can see a variety of acceptable looping/iteration techniques on display there as well.
std::vector<T> defines T operator[](int). This means you can access a vector x's element i via x[i].
std::string defines char operator[](int), which returns the char at that position within the string.
So if you have an std::vector<std::string> called x, x[i][j] will return the jth character of the string in the ith position of the vector.
This is not the idiomatic C++ way to do this - the most common means would be iterators (the .begin() and .end() calls). But since vector access is constant time (as is string-character access) it's not a huge deal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With