用模板栈实现字符串如I am a boy逆置成boy a am I,该如何解决
用模板栈实现字符串如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> > &'
求高手指教
------解决方案--------------------
stack<string> ptr;
应该是stact<char>
------解决方案--------------------
你声明的string类型的栈,push的是一个char,所以会报错。按照题意,你应该把句子分解成sub string,然后再push到栈
------解决方案--------------------
[code=C/C++][/code]
while(!ptr.empty())
{
cout<<ptr.top();
ptr.pop();
}
栈是string类型,而你传递的是char类型,,,改为stack<char>就好了,还有一个问题,最后你的栈内还存有字符没有输出,,,在函数后面加上上段代码
------解决方案--------------------
楼上错误,,,
以下是我的代码
#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> > &'
求高手指教
------解决方案--------------------
stack<string> ptr;
应该是stact<char>
------解决方案--------------------
你声明的string类型的栈,push的是一个char,所以会报错。按照题意,你应该把句子分解成sub string,然后再push到栈
------解决方案--------------------
[code=C/C++][/code]
while(!ptr.empty())
{
cout<<ptr.top();
ptr.pop();
}
栈是string类型,而你传递的是char类型,,,改为stack<char>就好了,还有一个问题,最后你的栈内还存有字符没有输出,,,在函数后面加上上段代码
------解决方案--------------------
楼上错误,,,
- C/C++ code
while(!ptr.empty()) { cout<<ptr.top(); ptr.pop(); }
------解决方案--------------------
- C/C++ code
while(!ptr.empty()) { cout<<ptr.top(); ptr.pop(); }