Yue*_*ang 4 c++ templates visual-studio c++11
我正在尝试在VS2013上使用C++实现最佳优先搜索.下面是代码.
//node for tree
struct Node
{
Node(std::string const& s, std::string const& p)
: state(s), path(p)
{}
const std::string state;
const std::string path;
};
//heuristic functor
struct ManhattanDistance
{
std::size_t operator()(std::string const& state, std::string const& goal)
{
std::size_t ret = 0;
for (int index = 0; index != goal.size(); ++index)
{
if ('0' == state[index])
continue;
auto digit = state[index] - '0';
ret += abs(index / 3 - digit / 3) + abs(index % 3 - digit % 3);// distance(row) plus distance(col)
}
return ret;
}
};
//functor to compare nodes using the heuristic function.
template<typename HeuristicFunc>
struct GreaterThan
{
explicit GreaterThan(HeuristicFunc h, std::string const& g = "012345678")
: goal(g), heuristic(h)
{}
bool operator()(Node const& lhs, Node const& rhs) const
{
return heuristic(lhs.state, goal) > heuristic(rhs.state, goal);
return true;
}
const std::string goal;
const HeuristicFunc heuristic;
};
Run Code Online (Sandbox Code Playgroud)
在单元测试中测试此代码时,编译器抱怨:
错误1错误C3848:类型为'const ai :: search :: ManhattanDistance'的表达式会丢失一些const-volatile限定符,以便调用'size_t ManhattanDistance :: operator()(const std :: string&,const std :: string &)"
如何理解这个错误?怎么解决?
cdh*_*wie 10
您的方法std::size_t ManhattanDistance::operator()(std::string const& state, std::string const& goal)
未声明const
,但您尝试在const ManhattanDistance
对象上调用它.编译器正确地拒绝了这个格式错误的程序.
更改定义行以声明方法const
:
std::size_t operator()(std::string const& state, std::string const& goal) const
// ^^^^^
Run Code Online (Sandbox Code Playgroud)