簡體   English   中英

為什么使用字符串會導致退出代碼 3 而使用 char[] 則不會

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

我正在練習我的編碼技能,我正在解決以下回溯問題(原始指南的解決方案也在那里)。

問題總結:

給定一個字符串,您需要打印所有可能的字符串,這些字符串可以通過在它們之間放置空格(零或一)來構成。

我的解決方案如下:

#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類的哪些屬性可能會引發此問題。 從我在網上找到的內容來看,我認為我在嘗試訪問字符串字符時訪問了內存中的非法位置,並且我認為問題出在我為buf保留內存空間的方式。

我想更深入地了解這個問題,如果有人能進一步解釋它的來源,我將不勝感激。

std::string::reserve()不會做您認為它會做的事情,即它不會增加字符串的實際大小。

改用std::string::resize()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM