How to get the difference of two points in a two dimensional array

#include <iostream>
using namespace std;
int main (int argc, char ** argv)
{
    int c;
    int distance=0;
    int largestdistance=0;
    int sum=0;
    cin >> c;
    int point[c][2];
    for (int i=0; i<c; i++){
        for (int j=0; j<2; j++){
            cin >> point[i][j];
        }
    }
    cout << point[2][0] << " ";
    for (int i=0; i<c; i++){
        for (int j=0; j<2; j++){
            sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]);
        }
        if (sum > largestdistance){
            largestdistance=sum;
        }
        cout << '\n';
        return 0;
    }
}

      

This program prints the absolute value of the first line of the first number minus the second number of the first line added to the absolute value of the second number of the first line, minus the second number of the second line. I was wondering how I could make the program so that it automatically executes sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1])

for everyone point[][]

up to sum += abs(point[c-1][0]-point[c][0])+abs(point[c-1][1]-point[c][1])

.

+3


source to share


1 answer


It would be much clearer if you put in the dot type:

struct Point {
    int x, y;
};

int manhattan_dist(const Point& p, const Point& q) {
    return abs(p.x - q.x) + abs(p.y - q.y);
}

      

Armed with this, it's much easier:

int sum = 0;
for (int i = 0; i < c - 1; ++i) {  // stop before c-1, so i and i+1 are valid
    sum += manhattan_dist(points[i], points[i+1]);
}

      



Btw int point[c][2];

is non-standard code because it is c

not a compile-time constant. You need to dynamically allocate the array:

Point* points = new Point[c];

      

or preferably:

std::vector<Point> points(c);

      

+2


source







All Articles