c++ 中的 abs() 错误

Error with abs() in c++

在此代码的第 35 行,abs() 函数出现错误。我选择的编译器:c++(4.3.2)

在底部查看错误。

void bfs(pair<int,int> pixelpos){
bfsq.push(pixelpos);
int u,v,i,j;
pair<int,int> tmpq;
while(!bfsq.empty()){
    tmpq = bfsq.front();
    u = tmpq.first; v = tmpq.second;
    bfsq.pop();
    r(i,u-square_dist,u+square_dist) r(j,v-square_dist,v+square_dist)
      if(inrange(i,j)){
      // ERROR HERE DOWN IN abs() fn
        int dist = abs(pixelpos.first - i) + abs(pixelpos.second -j); // Line: 35
        if(graph[i][j]>dist){
            graph[i][j] = dist;
            bfsq.push(pair<int,int> (i,j));
          }
      }
}

prog.cpp: 在函数中 'void bfs(std::pair)':

prog.cpp:35: 错误:重载 'abs(int)' 的调用不明确

/usr/include/c++/4.3/cmath:99: 注意:候选是:double std::abs(double) /usr/include/c++/4.3/cmath:103: 注意:浮动 std::abs(浮动)

/usr/include/c++/4.3/cmath:107: 注意:long double std::abs(long double)

prog.cpp:35: 错误:重载 'abs(int)' 的调用不明确

/usr/include/c++/4.3/cmath:99: 注意:候选人是:double std::abs(double)

/usr/include/c++/4.3/cmath:103: 注意:浮动 std::abs(浮动)

/usr/include/c++/4.3/cmath:107: 注意:long double std::abs(long double)

可能是什么原因?

错误的原因可能是您没有包含 header <cstdlib>.

#include <cstdlib>

标准 C 函数

int abs(int j);

在 C 中声明 header <stdlib.h>.

尽管 C++ 标准允许在全局命名空间中放置标准 C 名称,但是最好使用限定名称,例如

int dist = std::abs(pixelpos.first - i) + std::abs(pixelpos.second -j);