读书人

用模板栈兑现字符串如I am a bo

发布时间: 2012-10-21 09:00:07 作者: rapoo

用模板栈实现字符串如I am a boy逆置成boy a am I
以下是我的代码
#include<iostream>
#include<string>
#include<stack>
using namespace std;

void str(string st )
{
stack<string> ptr;
int length=st.size();
for(int j=length-1;j>=0;j--)
{
if(st[j]!=' ')
{
ptr.push(st[j]);
}
else
{
while(!ptr.empty())
{
cout<<ptr.top();
ptr.pop();
}
cout<<" "<<endl;
}

}

}

int main()
{
string p="i am boy";
str(p);
return 0;
}

出现错误error C2664: 'push' : cannot convert parameter 1 from 'char' to 'const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &'

求高手指教

[解决办法]
ptr是个string的容器,而你往里面push的是char型。
[解决办法]

C/C++ code
#include<iostream>#include<string>#include<stack>using namespace std;void str(string st ){    stack<char> ptr;    int length=st.size();    for(int i=0; i<length; ++i)        if(st[i] !=' ')            ptr.push(st[i]);    while(!ptr.empty())    {        cout<<ptr.top();        ptr.pop();    }    cout<<endl;}int main(){    string p="i am boy";    str(p);    return 0;} 

读书人网 >C++

热点推荐