Error with abs() in c++

爱⌒轻易说出口 提交于 2021-02-11 11:51:10

问题


Getting error with abs() function at line 35 in this code. Compiler I choosed : c++(4.3.2)

Look error at bottom.

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: In function 'void bfs(std::pair)':

prog.cpp:35: error: call of overloaded 'abs(int)' is ambiguous

/usr/include/c++/4.3/cmath:99: note: candidates are: double std::abs(double) /usr/include/c++/4.3/cmath:103: note: float std::abs(float)

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

prog.cpp:35: error: call of overloaded 'abs(int)' is ambiguous

/usr/include/c++/4.3/cmath:99: note: candidates are: double std::abs(double)

/usr/include/c++/4.3/cmath:103: note: float std::abs(float)

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

What might be the reason?


回答1:


The reason for the error can be that you did not include header <cstdlib>.

#include <cstdlib>

Standard C function

int abs(int j);

is declared in C header <stdlib.h>.

Though the C++ Standard allows to place standard C names in the global namespace nevertheless it is better to use qualified names as for example

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


来源:https://stackoverflow.com/questions/35378761/error-with-abs-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!