【发布时间】:2021-02-10 04:31:35
【问题描述】:
我正在练习我的编码技能,我正在解决以下backtracking problem(原始指南的解决方案也在其中)。
问题总结:
给定一个字符串,您需要打印所有可能的字符串,这些字符串可以通过在它们之间放置空格(零或一)来生成。
我的解决方案如下:
#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保留内存空间的方式上。
【问题讨论】:
-
阅读错误:“
Assertion '__pos <= size()' failed.”string::reserve 只分配内存,不会增加字符串的大小。
标签: c++ string c++11 char backtracking