我寫了一個函數,將字符串「rdd」的順序顛倒爲「ddr」, 當我運行它時出現子串超出範圍的錯誤。任何幫助表示讚賞!子串超出範圍
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
using namespace std;
string reverse(const string & s);
int main() {
cout << reverse("rdd") << endl;
}
string reverse(const string & s) {
string rname(s);
for (unsigned i = rname.size()-1; i >= 0; i--) {
cout << rname[i];
}
return rname;
}
你意識到這只是以相反的順序寫出字符串,但實際上並沒有反轉字符串,對吧?它複製提供的字符串,根本不會更改副本,並在以相反順序打印後返回未修改的副本。 – ShadowRanger
由於'i'是無符號的,因此當'i'爲0然後遞減時,它變成一個非常大的正數,因此超出範圍 – steveo225
而且變量'i'具有什麼值,當它的值等於' 0'(仍然滿足'i> = 0'條件),並且它被'i - '減1。 –