提问者:小点点

在C++中,我遇到了一个我无法理解的编译器错误


这是我的代码,它只是颠倒了句子:

#include <iostream>
#include <string>   

using namespace std;

int main()
{
    string sentence;
    string reversedSentence;
    int i2 = 0;

    cout << "Type in a sentence..." << endl;
    getline(cin, sentence);

    for (int i = sentence.length() - 1; i < sentence.length(); i--)
    {
        reversedSentence[i2] = sentence[i];
        i2++;
    }

    cout << reversedSentence << endl;
}

编译工作正常,但当我尝试运行程序时,会出现这种情况:

Type in a sentence...
[input]
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++-v3/include/bits/basic_string.h:1067: std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = unsigned int]: Assertion '__pos <= size()' failed.

共3个答案

匿名用户

您的ReversedSenture字符串为空,因此对其进行索引会调用未定义的行为。 相反,您可以使用push_back:

for (int i = sentence.length() - 1; i >= 0; i--)
{
    reversedSentence.push_back(sentence[i]);
}

还要注意,您的循环条件需要修改。 如果句子为空,则应将static_cast.length()转换为int,然后再减去1,如下所示:

for (int i = static_cast<int>(sentence.length()) - 1; i >= 0; i--)
{
    reversedSentence.push_back(sentence[i]);
}

您也可以使用一种算法来实现:

reversedSentence = sentence;
std::reverse(reversedSentence.begin(), reversedSentence.end());

这避免了语句字符串为空时的复杂性。

匿名用户

您的for-loop表示i<; sentence.length()是结束条件。 这导致它始终是true,并且永远不会访问for循环,因为您将i声明为sentence.length()-1。 这总是小于sentence.length()

匿名用户

我的建议是:不要使用指数。 更喜欢尽可能使用迭代器。

for (auto iter = sentence.rbegin(); iter != sentence.rend(); ++iter)
{
    reversedSentence.push_back(*iter);
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|遇|到了|理解|编译器)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?