关于逆置字符串和string成员函数assign的用法

otiru 2012-07-31 11:19:12
我想使用assign函数把字符串str1逆置到str2中,写了以下代码,但是无法通过编译
#include<iostream>
#include<string>

using namespace std;

int main()
{
string str1,str2;
str1="hello,world!";
str2.assign(str1.rbegin(),str1.rend());
cout<<str2<<endl;
}
rbegin()和rend()是string的成员啊,为什么不可以用,很难纳闷。。。改成str2.assign(str1.begin(),str1.end());就可以输出和str1一样的内容。。。求大神指教!!顺便给我个比较高效的字符串逆置的算法,感激不尽。
...全文
242 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
hen_hao_ji 2012-07-31
  • 打赏
  • 举报
回复

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int main()
{
string str1,str2;
str1="hello,world!";
// str2.assign(str1.rbegin(),str1.rend());
reverse(str1.begin(), str1.end());
cout<<str1<<endl;

return 0;
}

帅得不敢出门 2012-07-31
  • 打赏
  • 举报
回复
gcc 编译通过
./a.out
!dlrow,olleh
翅膀又硬了 2012-07-31
  • 打赏
  • 举报
回复
我用vs2008编译你的代码,能通过,并输出你期待的结果
翅膀又硬了 2012-07-31
  • 打赏
  • 举报
回复
我用vs2008运行你的代码,没问题,能输出你期望的结果
otiru 2012-07-31
  • 打赏
  • 举报
回复
看来是编译器的问题了,害我纠结半天。。
翅膀又硬了 2012-07-31
  • 打赏
  • 举报
回复
我试了一下在6.0上面也不行, 6.0版本的相关函数跟以后版本的不一样 assign 所在的头文件,6.0版本的XSTRING共627行。VS2008的xstring有2242行呢[Quote=引用 5 楼 的回复:]
你们可以编译通过上面的代码??我用VC++6.0不可以啊。。难道我的编译器有问题??这是我的编译器提示的错误:error C2664: 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &__thiscall std::basic_string<char,stru……
[/Quote]
otiru 2012-07-31
  • 打赏
  • 举报
回复
你们可以编译通过上面的代码??我用VC++6.0不可以啊。。难道我的编译器有问题??这是我的编译器提示的错误:error C2664: 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &__thiscall std::basic_string<char,struct std::char_traits<c
har>,class std::allocator<char> >::assign(const char *,unsigned int)' : cannot convert parameter 1 from 'class std::reverse_iterator<char *,char,char &,char *,int>' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧