Reputation: 83
I'm trying to use a container to store the iterator of string s
, but I got segment fault when I run it. As you will see in the following, the error seems to come with char temp = **itbegin;
, it might means I can't assign any value via the previous iterator.
Why is it? Did I misuse the iterator?How to use the iterator properly?
#include <iostream>
#include <vector>
using namespace std;
string reverseVowels(string s);
int main()
{
string s ="hello";
cout << reverseVowels(s);
}
string reverseVowels(string s) {
string::iterator iter = s.begin();
string::iterator iterend = s.end();
vector<string::iterator> iteratorbox;
for(;iter != iterend ; ++iter){
if((*iter) == 'a' &&
(*iter) == 'e' &&
(*iter) == 'i' &&
(*iter) == 'o' &&
(*iter) == 'u'){
iteratorbox.push_back(iter);
}
}
auto itbegin = iteratorbox.begin();
auto itend = iteratorbox.end() ;
--itend;
//for(;itbegin < itend ; ++itbegin, --itend)
{
char temp = **itbegin;
// *(*itbegin) = *(*itend);
// *(*itend) = temp;
}
return s;
}
Upvotes: 2
Views: 109
Reputation: 70506
The answer by @rems4e is perfectly fine, but I find such code easier to read and less error-prone if you put the vowels into an array
char const vowels[] = { 'a', 'e', 'i', 'o', 'u' };
so that you can encapsulate the matching logic inside your reverseVowels
into the Standard algorithm any_of
if (std::is_any_of(std::begin(vowels), std::end(vowels), [](auto const& v) {
return *iter == v;
}) {
iteratorbox.push_back(iter);
}
This avoids much of the repetitive testing (which can get out-of-sync quickly should you ever use a different alphabet (German e.g.))
Upvotes: 0
Reputation: 3172
Your problem comes from the condition upon which you insert iterators in your iteratorbox
vector.
You used the &&
operator, implying that every letter of the string has to be equal to all vowels at the same time. This means no iterator will be inserted, and you are then trying to dereference the begin()
iterator of the vector, which happens to be its past-the-end iterator. This causes undefined behavior, which in your case manifests itself as a crash.
You probably meant to use
((*iter) == 'a' ||
(*iter) == 'e' ||
(*iter) == 'i' ||
(*iter) == 'o' ||
(*iter) == 'u')
as a condition.
Upvotes: 5