简体   繁体   English

如何正确使用此迭代器?

[英]How to use this iterator properly?

I'm trying to use a container to store the iterator of string s , but I got segment fault when I run it. 我正在尝试使用一个容器来存储字符串s的迭代器,但是运行它时出现了段错误。 As you will see in the following, the error seems to come with char temp = **itbegin; 正如您将在下面看到的那样,该错误似乎与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;
}

Your problem comes from the condition upon which you insert iterators in your iteratorbox vector. 您的问题来自在iteratorbox向量中插入迭代器的条件。

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. 这意味着将不插入迭代器,然后您尝试取消引用向量的begin()迭代器,而恰好是其过去的迭代器。 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. 作为条件。

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 @ rems4e的答案非常好,但是如果您将元音放入数组中,我发现这样的代码更易于阅读且不易出错

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 这样就可以封装你里面的匹配逻辑reverseVowels到标准算法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 eg)) 这样就避免了很多重复的测试(如果您使用其他字母(例如德语),该测试可能会很快变得不同步)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM