Asm
Asm

Reputation: 19

Working with coordinates x y

I need to read from a file coordinates of points. The file looks like this:

x0 y0

x1 y1

....

Then find center and diameter of the smallest enclosing circle. But I stucked in the beginning. I don't know how to hold coordinates and decided to choose array of structures. I've read coordinates into structure. I'm going to make 4 conditions:

1 - There is one point and you can't find the smallest enclosing circle.

2 - There are 2 points. Now the task is to find distance between them and its center.

3 - There are 3 points.

4 - More than 3 points. Use of special algorithm

I tried to use vector. I don't know how to use my points (elements of vector) later in functions etc.

#include "stdafx.h"
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

// Distance
float distance(){
    return  sqrt((point[0].x * point[1].x) + (point[0].y * point[1].y));
}

struct Points
{
    float x, y;
};

int _tmain(int argc, _TCHAR* argv[])
{
vector<Points> point;
Points tmp;

ifstream fin("Points.txt");

if (!fin.is_open())
    cout << "Cannot open the file \n";
else{
    while (fin >> tmp.x >> tmp.y){
        point.push_back(tmp);
        cout << tmp.x << tmp.y << endl;
    }
    fin.close();

}

return 0;
}

Upvotes: 0

Views: 26263

Answers (1)

David K
David K

Reputation: 3132

I would name the struct something like Point rather than Points, since a single instance of the struct holds only one pair of x,y coordinates.

Then a suitable distance function might be something like

float distance(const Point& point1, const Point& point2)
{
  return  sqrt((point1.x * point2.x) + (point1.y * point2.y));
}

You can get the distance between any two points in your input set like this:

distance(point[i], point[j])

You might also want to measure the distances from your input points to a point that is not in the set, such as a point where you think the center of the circle might be. For example,

distance(point[i], candidate_center_of_circle)

If it were my code, I would likely make Point a class and give it a member function for distance so that I could write something like

candidate_center_of_circle.distanceTo(point[i])

By the way, I might name the variable points rather than point because it is a vector that holds multiple instances of Point. If you intend to write things like point[i] a lot you might not like points[i], but if you are mostly going to make STL iterators over the vector then you would have something like this:

for (std::vector<Point>::const_iterator it = points.begin(); it != points.end(); ++it)

Upvotes: 2

Related Questions