你好,我有一个简单的 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
至于你的说法
I know reserve can be used i.e. the program works using
string s1;
s1.reserve(1);
那就错了。该算法的调用将具有未定义的行为,因为 s1 还没有元素,您可能无法取消引用迭代器。
关于c++ - 在 C++ 中初始化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30953145/