嗨,我有一个简单的C ++程序。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string s = "Rotate this";
rotate(s.begin(),s.begin()+6,s.end());
cout<<s<<endl;
string s1;
rotate_copy(s.begin(),s.begin()+4,s.end(),s1.begin());
cout<<s1<<endl;
}
该程序失败(运行时错误),因为s1.begin()
迭代器未指向任何内容。如何初始化s1
字符串,使其为空并s.begin()
可以使用?
我知道reserve
可以使用,即程序使用
string s1;
s1.reserve(1);
但我想必须有其他方法可以解决这个问题。
首先,您应该包含标题 <string>
#include <string>
因此,s1
您应该为其保留与大小相等的内存,s
并使用标准的迭代器适配器std::back_insert_ietrator
例如
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
int main()
{
std::string s = "Rotate this";
std::rotate( s.begin(), std::next( s.begin(), 6 ), s.end() );
std::cout << s << std::endl;
std::string s1;
s1.reserve( s.size() );
std::rotate_copy( s.begin(), std::next( s.begin(), 4 ), s.end(),
std::back_inserter( s1 ) );
std::cout << s1 << std::endl;
}
程序输出为
thisRotate
sRotate thi
至于你的声明
我知道可以使用储备金,即程序可以使用
string s1;
s1.reserve(1);
那是错误的。该算法的调用将具有未定义的行为,因为s1还没有元素,并且您可能未取消引用迭代器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句