gpt4 book ai didi

c++ - cpp 这个函数中的奇怪行为

转载 作者:行者123 更新时间:2023-11-28 04:32:24 25 4
gpt4 key购买 nike

我正在尝试编写一个函数来计算启发式间隙。下面是我的代码:

#include <iostream>
using namespace std;
#include <vector>
#include <map>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
string direction = "backward";
string state_string = "012345";
string goal_state_string = "125430";
int n = 3;

string ignored_pancakes;
int gap = 0;
state_string += to_string(state_string.length());
unsigned int goal_state_index;
goal_state_string += to_string(goal_state_string.length());
if (direction == "forward")
{
for (unsigned int i = 0; i < n; i++)
{
ignored_pancakes += goal_state_string[i];
}
}
else
{
for (unsigned int i = 0; i < n; i++)
{
ignored_pancakes += state_string[i];
}

}

for (int i = 0; i < state_string.length(); i++)
{

if ((ignored_pancakes.find(state_string[i + 1]) != string::npos) or (ignored_pancakes.find(state_string.at(i)) != string::npos))
{
continue;
}

if (abs(goal_state_string.find(state_string[i])-goal_state_string.find(state_string[i+1])!=1)){
gap++;
}


cout << state_string.at(i) << "\t" << state_string.at(i + 1) << endl;
}
// cout << state_string << endl;
cout << ignored_pancakes << endl;
cout << gap << endl;
}

我期望的输出如下:

3       4
4 5
5 6
012
2

但是打印出来的是:

3       4
4 5
5 6

奇怪的是,当我注释掉以下内容时:

cout << state_string.at(i) << "\t" << state_string.at(i + 1) << endl;

输出是:

012
2

为什么它会打印出完全不同的内容,具体取决于看起来无关紧要的行。

最佳答案

for (int i = 0; i < state_string.length(); i++)
{
// ...
cout << state_string.at(i) << "\t" << state_string.at(i + 1) << endl;
}

使用 i + 1 您正在越界访问字符串。将循环更改为

for (int i = 0; i < state_string.length() - 1; i++)

关于c++ - cpp 这个函数中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52529210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com