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

E. *_*urg 2 c++ string char backtracking c++11

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

问题总结:

给定一个字符串,您需要打印所有可能的字符串,这些字符串可以通过在它们之间放置空格(零或一)来构成。

我的解决方案如下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的解决方案与指南的解决方案非常相似,只是我用于std::string缓冲区变量而不是char[]像指南那样。

我试图了解std::string该类的哪些属性可能会引发此问题。从我在网上找到的内容来看,我认为在尝试访问字符串字符时访问了内存中的非法位置,并且我认为问题出在我在内存中为buf.

我想更深入地了解这个问题,如果有人能进一步解释它的来源,我将不胜感激。

小智 8

std::string::reserve() 不会做你认为它会做的事情,即它不会增加字符串的实际大小。

使用std::string::resize()来代替。