c++ - 在 C++ 中初始化字符串

标签 c++ string stl

你好,我有一个简单的 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/

相关文章:

c++ - 在 C++ 中反转数组时,为什么我在输入和输出之间得到一个 "random"数字?

C#字符串操作问题

c++ - 我想根据自己的参数使用 count_if

c++ - 使用 C++ 和 Windows API 以编程方式更改墙纸

c# - Windows 钩子(Hook)的奇怪行为

c++ - 静态成员的继承与保护

python - 从字符串中删除元音

Python:分割和分析字符串的最有效方法

C++按值而不是按位置删除 vector 元素?

c++ - 为什么将函数包装到 lambda 中可能会使程序更快?