《C算法》读书笔记 (1):xutility(764) error C2039

3-8程序 最近点计算

看上去好像没有任何问题(从原书上摘下来的程序,稍微做了点改动),但是VS2008会报25个error。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

struct Point
{
    float fx, fy;
};

int n;
float d;

float distance(Point &lhs, Point &rhs)
    {
        return sqrt((lhs.fx - rhs.fx) * (lhs.fx - rhs.fx) + (lhs.fy - rhs.fy) * (lhs.fy - rhs.fy));
    }

float randFloat()
{
    return 1.0 * rand() / RAND_MAX;
}

int main()
{
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);

    srand(0);
    scanf("%d%lf", &n, &d);

    Point *pt;
    pt = (Point*)malloc(n * sizeof(Point));
    for(int i = 0; i < n; ++ i)
    {
        pt[i].fx = randFloat(); pt[i].fy = randFloat();
    }
    float min_dist = distance(pt[0], pt[1]);
    int cnt = 0;
    for(int i = 0; i < n; ++ i)
    {
        for(int j = i + 1; j < n; ++ j)
        {
            float temp = distance(pt[i], pt[j]);
            min_dist = min(min_dist, temp);
            if(temp < d)
                ++ cnt;
        }
    }
    printf("min_dist = %.6f\n", min_dist);
    printf("cnt = %d\n", cnt);

    free(pt);
    return 0;
}

例如下面这种莫名其妙的错误
xutility(764) : error C2039: “iterator_category”: 不是“Point”的成员

问题出在哪儿?原来std命名空间里面也有一个distance函数,编译器无法得知采用哪个函数。
解决的方法很简单:自定义一个命名空间myNamespace

namespace myNamespace
{
    float distance(Point &lhs, Point &rhs)
    {
        return sqrt((lhs.fx - rhs.fx) * (lhs.fx - rhs.fx) + (lhs.fy - rhs.fy) * (lhs.fy - rhs.fy));
    }
}

使用的方法和std::min等类似

float min_dist = myNamespace::distance(pt[0], pt[1]);
    int cnt = 0;
    for(int i = 0; i < n; ++ i)
    {
        for(int j = i + 1; j < n; ++ j)
        {
            float temp = myNamespace::distance(pt[i], pt[j]);
            min_dist = min(min_dist, temp);
            if(temp < d)
                ++ cnt;
        }
    }

很明显,这个算法的时间复杂度是

O(n2)

你可能感兴趣的:(C算法读书笔记)