Getting an error while reversing vowels in a string

I'm writing a code to reverse vowels in a string. I first took all the vowels of a string into a vector and then I looped the string from backwards by replacing the vowels but I keep getting an error.

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
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

string reverseVowels(string s)
{
	vector<char>v;
	vector<char>v2;
	char c;
	for (int i = 0; i < s.size(); i++)
	{
                //taking all the vowels of the string into a vector
		if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
		{
			v.push_back(s[i]);
		}
	}

        //reversing the vowels of the string
	for (int i = s.size() - 1; i >= 0; i--)
	{
		if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u')
		{
			s[i] = v[i];  //Getting an error here
		}
	}
	return s;
}

int main()
{
        //Required output is "holle"
	string s = "hello";
	string p = reverseVowels(s);
	cout << p << endl;
	return 0;
}
Last edited on
You're trying to read from v[4] but v is only of size 2.
Last edited on
@philip92, @Repeater has the source of the crash.

Now, consider what your plan is. Currently, you are storing the vowel itself in v.

That doesn't really help you that much. Consider storing the location(s) where you found a vowel.

A location will not be a char, so "v" should probably be a type suitable to store a location.

Start thinking along those lines and that should lead you toward a better direction.
Registered users can post here. Sign in or register to post.