简体   繁体   中英

how to get the difference of two points in a 2D 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 out the value of the absolute value of the first row first number minus the second row first number added to the absolute value of the first row second number minus the second row second number. I was wondering that how do I make the program so that it automatically does the sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]) for all point[][] all the way up to sum += abs(point[c-1][0]-point[c][0])+abs(point[c-1][1]-point[c][1]) .

This would be a lot clearer if you introduced a point 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 that, it's a lot easier to loop:

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 c is not a compile-time constant. You need to dynamically allocate the array:

Point* points = new Point[c];

or, preferably:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM