问题
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