为什么我在这里得到一个内存相关的错误
Why did I get a Memory-related error here?
我遇到了一个来自网站的问题。给定string
, s
和st
,我必须找到s
中st
的所有可能组合。例如,
s = "doomdogged"
st = "dg"
answer = 4
我可以从0或4中选择d,从6或7中选择g。这给了我4种可能的组合。
下面是我的代码:
#include <iostream>
#include <vector>
using namespace std;
string s, st;
bool target[26];
vector<int> positions[26];
vector<vector<int>> possibleCombinations;
void DFS_Enumeration(int, vector<int>*);
int DFS_index_max = 0;
int main(int argc, char *argv[])
{
int answer = 0;
cin >> s; //Given a string s
cin >> st; //Given a string st
//Find all possible combination of st in s
for ( int i = 0 ; i < 26 ; ++ i )
target[i] = 0;
for ( int i = 0 ; i < st.length() ; ++ i )
target[st[i] - 97] = 1;
for ( int i = 0 ; i < 26 ; ++ i )
{
if ( target[i] == 0 ) continue;
for ( int j = 0 ; j < s.length() ; ++ j )
{
if ( s[j] == i + 97 ) positions[i].push_back(j);
}
}
DFS_index_max = st.length();
vector<int> trail(0);
DFS_Enumeration(0, &trail); //Here I got an runtime error
for ( vector<int> vi : possibleCombinations )
{
int currentMax = 0;
for ( int i = 0 ; i < vi.size() ; ++ i )
{
if ( vi[i] > currentMax )
{
if ( i == vi.size() - 1 ) ++ answer;
currentMax = vi[i];
continue;
}
else
break;
}
}
cout << answer;
}
void DFS_Enumeration(int index, vector<int>* trail)
{
if ( index == DFS_index_max )
{
possibleCombinations.push_back(*trail);
return;
}
for ( int i = 0 ; i < positions[st[index] - 97].size() ; ++ i )
{
trail -> push_back(positions[st[index] - 97][i]);
DFS_Enumeration(++index, trail);
trail -> pop_back();
}
return;
}
首先,我在st
中查找字符,并根据需要标记它们,以便在我的布尔数组目标中找到。
然后,使用DFS枚举所有可能的组合。对于上面的"doom顽强"answers"dg"的例子,d存在于0、4、9中。g存在于6和7中。我将得到06、07、46、47、96、97。
最后,我计算那些有意义的,并输出答案。由于某种原因,我的代码不能工作,并在我标记的行生成一个关于内存的运行时错误。
DFS_Enumeration
可能会将index
递增任意次数,因此st[index]
可能会超过字符串st
的末尾。
相关文章:
- 重新定位图像时如何前进到下一个内存块
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 是否可以通过每次在内存中仅保存一个平铺来处理完整的平铺 tiff 图像?
- 如何使用带有矢量的 winapi 读取进程内存从另一个进程读取缓冲区?
- 是否可以使用分配器对象来释放另一个分配器分配的内存?
- 我有一个线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)错误.我认为这是由于内存管理不好.我可以
- C++,一个内存块与多个内存块
- C++强制变量到一个固定的内存位置
- 使用一个内存集数组和单个堆栈在 O(n) 中查找数组的下一个更大元素
- 在没有任何锁的情况下加入另一个线程后是否需要内存围栏?
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 如何将矩阵的行随机复制到内存中的另一个矩阵的过程并行化?
- 在C++中分配一个大内存块
- 需要在内存C++中放置一个浮点数作为十六进制
- 为什么 valgrind 报告两个内存分配,而我的代码只请求一个?
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 目标c是否需要一个标准来定义像c++11这样的内存模型
- 你能在链表中有一个动态数组和它的内存分配吗
- c++如何分配内存一个类似T*var[1]的数组