vector<> function whale_talk

I think I do not fully understand vector function. I don't know what's going on during for loops part in this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include <iostream>
#include <vector>
#include <string>

int main() {

  std::string input = "Turpentine and turtles.";

  std::vector<char> vowels = {'a', 'e', 'i', 'o', 'u'};



  std::vector<char> whale_talk;

  for (int i = 0; i < input.size(); i++) {

    for (int j = 0; j < vowels.size(); j++) {

      if (input[i] == vowels[j]) {

        whale_talk.push_back(input[i]);

        if (input[i] == 'e' || input [i] == 'u') {

        whale_talk.push_back(input[i]);

        }

      }

    }

  }

  for (int k = 0; k < whale_talk.size(); k++) {

    std::cout << whale_talk[k];

  }

  std::cout << "\n";

}
So what are the lines you have problems with?

It looks rather straightforward. It filters out the vowels and doubles 'u' and 'e'.
I cannot understand
for (int i = 0; i < input.size(); i++) {

for (int j = 0; j < vowels.size(); j++) {

if (input[i] == vowels[j]) {

whale_talk.push_back(input[i]);

if (input[i] == 'e' || input [i] == 'u') {

whale_talk.push_back(input[i]);

}
this line. I think what I need is just one sentence in each line.
.size() is the number of elements in the vector.

[i] is the ith element of the vector - where elements start at 0

.push_back() adds the specified element to the end of the vector

See http://www.cplusplus.com/reference/vector/vector/
it may be hard to follow because it is written very oddly -- instead of a string, they use vector char and manually print it, and instead of a smart isvowel tool they search by brute force through a list.

for every letter in input
for every letter in vowel
if the letter is a vowel
put it into the result once
and if it is a u or e, put it in a second time
@OP - Here's a cleaned-up up version of your program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <vector>
#include <string>

//  Return true if character c found
//  Return false if character c not found
bool isVowel(const char c)
{
    const std::string vowels = "aeiou";
    return vowels.find(c) != std::string::npos;
}

int main() 
{
    std::string input = "Turpentine and turtles.";
    std::string whale_talk;
    std::string::const_iterator citer;

    for (auto c : input)    //  range based for loop 
    {
        if (isVowel(c))     //  Teest each character of input    
        {
            whale_talk.push_back(c);    //  Append the character
            if (c == 'e' || c == 'u') 
            {
                whale_talk.push_back(c);    //  Append the character
            }
        }
    }

    std::cout << whale_talk << std::endl;    //  Output the string
}

Thank you so much!
Topic archived. No new replies allowed.