c++ - 在 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.
解决方案
您的reversedSentence
字符串为空,因此对其进行索引会调用未定义的行为。相反,您可以push_back
像这样使用:
for (int i = sentence.length() - 1; i >= 0; i--)
{
reversedSentence.push_back(sentence[i]);
}
另请注意,您的循环条件需要修改。如果sentence
是空的,你应该static_cast
在减去 1 之前,像这样.length()
:int
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());
这避免了sentence
字符串为空时的复杂性。
推荐阅读
- pelican - 如何从模板中获取 Pelican 版本号
- jquery - 在jquery自动完成中设置值
- python - 如何平均划分多个列表?[Python]
- git - 通过 http 访问远程服务器上的 ungit
- tensorflow - 在 Anaconda venv tensorflow_cpu 版本中训练时出现新手错误后出现名为 Unknown Meta Architecture 的错误
- angular - 访问模板中的新属性
- c - 使用 MPI_Send 和 MPI_Recv 传递数组时出错
- javascript - Google表格脚本将输入字段答案移动到空白输出字段
- python - 梯度提升 - 基于月份的价格预测
- windows - DebugActiveProcessStop 是否关闭句柄?