問題是反轉字串中的單詞......
Eg. - This is Nice
Output -Nice is This
所以這是錯誤
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_create
這是我的實際代碼,不知道哪里出了問題我剛開始使用 C ,但我確定我正在嘗試訪問未定義的索引。如果我錯了請糾正我
string reverseWords(string s) {
vector<string> v;
string x="";
for(int i=0;i<s.size();i )
{
if(isspace(s[i]))
{
v.push_back(x);
x="";
v.push_back(" ");
}
else
{
x=x s[i];
}
}
v.push_back(x);
x="";
for(int j=v.size();j>=0;j--) x=x v[j];
return x;
}
uj5u.com熱心網友回復:
你的方法效率低下。
此外,您不是在反轉源字串,而是以相反的順序構建新字串。
if陳述句的復合陳述句
if(isspace(s[i]))
{
v.push_back(x);
x="";
v.push_back(" ");
}
當源字串包含相鄰空格時沒有多大意義,因為它會將空字串附加到向量。
此外,如果字串的最后一個字符是空格,那么 for 回圈之后的這條陳述句
v.push_back(x);
再次向向量附加一個冗余的空字串。
這個for回圈
for(int j=v.size();j>=0;j--) x=x v[j];
j等于時呼叫未定義的行為v.size()。
如果您正在處理該型別的物件,std::string那么您應該使用該類的方法和標準演算法,例如 algorithm std::reverse。
下面是一個演示程式,展示了如何反轉字串。
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
std::string & reverseWords( std::string &s, const char *delim = " \t" )
{
auto first = s.find_first_not_of( delim );
if (first != std::string::npos)
{
auto last = s.find_last_not_of( delim ) 1;
std::reverse( std::next( std::begin( s ), first ), std::next( std::begin( s ), last ) );
while ( first != last )
{
auto pos = s.find_first_of( delim, first );
if (pos == std::string::npos) pos = last;
std::reverse( std::next( std::begin( s ), first ),
std::next( std::begin( s ), pos ) );
first = pos;
if ( first != last ) first = s.find_first_not_of( delim, first );
}
}
return s;
}
int main()
{
std::string s( "The quick brown fox jumps over the lazy dog" );
std::cout << s << '\n';
std::cout << reverseWords( s ) << '\n';
}
程式輸出是
The quick brown fox jumps over the lazy dog
dog lazy the over jumps fox brown quick The
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/533659.html
標籤:C 细绳算法撤销函数定义
