I'm having trouble with the following code and can't seem to figure out what is wrong
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
double distance(int a, int b)
{
return fabs(a-b);
}
int main()
{
vector<int> age;
age.push_back(10);
age.push_back(15);
cout<<distance(age[0],age[1]);
return 0;
}
The error lies at calling of function distance.
/usr/include/c++/4.6/bits/stl_iterator_base_types.h: In instantiation of ‘std::iterator_traits<int>’:
test.cpp:18:30: instantiated from here
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:166:53: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:167:53: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:168:53: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:169:53: error: ‘int’ is not a class, struct, or union type
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:170:53: error: ‘int’ is not a class, struct, or union type
You are trying to override std::distance function, try removing "using namespace std
" and qualifying cout
and endl
with std::
#include <iostream>
#include <cmath>
#include <vector>
double distance(int a, int b)
{
return fabs(a-b);
}
int main()
{
std::vector<int> age;
age.push_back(10);
age.push_back(15);
std::cout<< distance(age[0],age[1]);
return 0;
}
The std::distance
is used to count the number of elements in a container within a specified range. You can find more about it here.
Or you can rename your distance function if you want to introduce the std::
namespace:
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
double mydistance(int a, int b)
{
return fabs(a-b);
}
int main()
{
vector<int> age;
age.push_back(10);
age.push_back(15);
cout<<mydistance(age[0],age[1]);
return 0;
}
This will make your code work, but it is not recommended to have "using namespace" declarations before definitions. When you write your code, you should avoid the second option, it's shown here only as an alternative for your code example.
How about
cout<< ::distance(age[0],age[1]);
(other answers already suggest removing the using
directive).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With