为什么使用字符串会导致退出代码 3 而使用 char[] 不会

Why using string results in exit code 3 and using char[] doesnt

我正在练习我的编码技能,我正在解决以下问题 backtracking problem(原始指南的解决方案也在那里)。

问题总结:

Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.

我的解决方案如下:

#include <iostream>
#include <cstring>
#include <string>


using namespace std;

void permutationWithSpacesAux(const char* s, string buf, int s_index, int b_index, int len_s){

    // stop condition
    if(s_index == len_s){
        cout << buf << endl;
        return;
    }
    // print w\o space
    buf[b_index] = s[s_index];
    // recursive call w\ next indices
    permutationWithSpacesAux(s, buf, s_index + 1, b_index + 1, len_s);

    // print w\ space
    buf[b_index] = ' ';
    buf[b_index + 1] = s[s_index];
    // recursive call w\ next indices
    permutationWithSpacesAux(s, buf, s_index + 1, b_index + 2, len_s);
}

void permutationWithSpaces(const char* s){
    int n = strlen(s);
    string buf;
    buf.reserve(2*n);
    buf[0] = s[0];
    permutationWithSpacesAux(s,buf, 1, 1,n);
}

int main() {
    const char* s = "ABCD";
    permutationWithSpaces(s);
    return 0;
}

这是我得到的错误:

C:\Users\elino\CLionProjects\permutationWithSpaces\cmake-build-debug\permutationWithSpaces.exe
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++-v3/include/bits/basic_string.h:1067: std::__cx
x11::basic_string<_CharT, _Traits, _Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[](st
d::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; _Traits = std::char_traits<char>; _Al
loc = std::allocator<char>; std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; std::__cxx11::basic_
string<_CharT, _Traits, _Alloc>::size_type = unsigned int]: Assertion '__pos <= size()' failed.

Process finished with exit code 3

我的解决方案与指南的解决方案非常相似,只是我使用 std::string 作为缓冲区变量而不是指南使用的 char[]

我正在尝试了解 std::string class 的 属性 会引发此问题。根据我在网上找到的内容,我认为我在尝试访问字符串字符时访问了内存中的非法位置,我认为问题出在我在内存中为 buf 保留 space 的方式.

std::string::reserve() 并没有像您想象的那样做,即它不会增加字符串的实际大小。

改用std::string::resize()