我正在尝试编写一个计算间隙启发式的函数。下面是我的代码:
#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/