在C++中使用向量

18

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

#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;
}

错误在调用函数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

我想将数据存储在向量数组中(用于动态大小),然后计算数据点之间的距离。 - Dzung Nguyen
4个回答

33
您正在尝试覆盖std::distance函数,请尝试去除"using namespace std",并将coutendlstd::限定符限定。
#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;
}

std::distance用于计算指定范围内容器中元素的数量。您可以在 这里 找到更多信息。

或者,如果您想引入std::名称空间,可以将您的距离函数重命名:

#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;
}

这会使您的代码工作,但在定义之前使用"using namespace"声明并不推荐。编写代码时,应避免第二种选项,它仅作为代码示例的替代方法。


2
或者你可以重命名自己的距离函数,避免与 std::distance 冲突。 - Mithrandir
1
@Mithrandir 这是一个快速而廉价的解决方案。我更喜欢海报的答案。 - Caesar
6
@Mithrandir 不,"simply" 的意思是 "不要把另一个命名空间带到全局命名空间中",因为那就是它们存在的原因! - Griwes
3
@Mithrandir:命名空间的存在是为了使您能够重复使用名称。如果您担心名称冲突和编写与此相关的代码,那么您可能没有正确使用命名空间,或者没有理解它们的作用。 - Sebastian Mach

9

How about

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

(其他答案已经建议删除using指令。)

3
了解作用域解析运算符的范围是有价值的,但除非避免使用会导致很大问题,否则不应该在生产代码中使用它。尽管如此,因为这是一条有用的小知识点,所以还是要给一个加一的赞。 - dmckee --- ex-moderator kitten

4

当你创建自己的名为distance的函数时,不要使用using namespace 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.
}

看起来他有自己的“distance”实现。 - CAMOBAP

0

或者,你可以使用

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接