C++ 向量在C++;

C++ 向量在C++;,c++,vector,C++,Vector,我在以下代码中遇到了问题,似乎无法找出问题所在 #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.pu

我在以下代码中遇到了问题,似乎无法找出问题所在

#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;
}
#包括
#包括
#包括
使用名称空间std;
双倍距离(整数a、整数b)
{
返回晶圆厂(a-b);
}
int main()
{
媒介年龄;
年龄。推回(10);
年龄。推回(15);

cout在创建自己的名为
distance
的函数时,不要使用
使用命名空间std
,因为对
distance
的调用是在查找
std::distance
函数,而不是
distance
函数

您也可以这样做:

namespace foo
{
  double distance(int a, int b)
  {
    return fabs(a-b);
  }
}

int main()
{
   foo::distance(x,y); //now you're calling your own distance function.
}

您试图覆盖std::distance函数,请尝试删除“
使用命名空间std
”并使用
std:
限定
cout
endl

#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;
}
这将使您的代码正常工作,但不建议在定义之前使用“using namespace”声明。编写代码时,应避免使用第二个选项,此处仅作为代码示例的替代选项显示。

如何

cout<< ::distance(age[0],age[1]);

cout或者,您可以使用

 using foo::distance; // OR:
 using namespace foo;

 (distance)(x,y); // the (parens) prevent ADL

我想将数据存储在向量数组中(用于动态大小),然后计算数据点之间的距离。看起来他有自己的
distance
实现,或者简单地重命名您自己的距离函数,并消除与
std::distance
@Mithrandir的冲突,这是一个快速且廉价的解决方案。我更喜欢海报式的答案。@Mithrandir,不,“simply”是“不要将另一个命名空间引入全局命名空间",因为这就是我们拥有它们的原因!@Mithrandir:namespaces是为了让您能够重用名称。如果您担心名称冲突和名称周围的代码,那么您使用的名称空间是错误的,或者不理解它们。关于范围解析操作符,这是一件值得了解的事情,但我不会将其放在生产代码中,除非避免它会导致big、 大问题。尽管如此,有用的琐事还是+1。
cout<< ::distance(age[0],age[1]);
 using foo::distance; // OR:
 using namespace foo;

 (distance)(x,y); // the (parens) prevent ADL