将向量成员(struct)传递给函数

aro*_*oup 1 c++ structure vector

我在跟随代码行时遇到错误.我试图将向量p的元素p [0],p [1],p [2],p [3]传递给函数距离.

typedef struct {
     long long x,y;
} point; 

long long distance (point A,point B)
{
    int d1 = A.x - B.x ;
    int d2 = A.y - B.y ;
    long long d = d1 * d1 + d2 *d2 ;
    return d ;
}

 //in main function I declared vector <point> p and took input and then,
    x1 = distance (p[0],p[1]) ; // this line is causing error
    x2 = distance (p[1],p[2]) ; // this line is causing error
    x3 = distance (p[2],p[3]) ; // this line is causing error
    x4 = distance (p[3],p[0]) ; // this line is causing error
Run Code Online (Sandbox Code Playgroud)

产生的错误:

In file included from /usr/include/c++/4.6/bits/stl_algobase.h:66:0,
                 from /usr/include/c++/4.6/bits/char_traits.h:41,
                 from /usr/include/c++/4.6/ios:41,
                 from /usr/include/c++/4.6/ostream:40,
                 from /usr/include/c++/4.6/iostream:40,
                 from d.cpp:19:
/usr/include/c++/4.6/bits/stl_iterator_base_types.h: In instantiation of ‘std::iterator_traits<point>’:
d.cpp:83:27:   instantiated from here
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:166:53: error: no type named ‘iterator_category’ in ‘struct point’
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:167:53: error: no type named ‘value_type’ in ‘struct point’
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:168:53: error: no type named ‘difference_type’ in ‘struct point’
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:169:53: error: no type named ‘pointer’ in ‘struct point’
/usr/include/c++/4.6/bits/stl_iterator_base_types.h:170:53: error: no type named ‘reference’ in ‘struct point’
Run Code Online (Sandbox Code Playgroud)

需要帮助.

Som*_*ude 8

这很可能是因为你有

using namespace std;
Run Code Online (Sandbox Code Playgroud)

在你的代码中.这使编译器认为您正在引用std::distance而不是您的函数.

显而易见的解决方案,以及我真正推荐的解决方案是停止使用using namespace std;您的代码.在此期间,您可以尝试使用全局范围调用您的函数,例如

x1 = ::distance (p[0],p[1]);
Run Code Online (Sandbox Code Playgroud)

  • @aroup强调破坏性`使用命名空间std`是非常重要的.您应该尝试不在任何地方*使用它,除非可能在非常小的范围内,在这种情况下它无论如何都不会产生任何优势.不幸的是,每当我说出来时,我都会与其他人相提并论,他们认为在实施文件中不加选择地使用它是绝对安全的.正如你所发现的那样,它不是. (3认同)