简体   繁体   中英

C++ calculate difference between two elements in a vector

I have a 2 vectors of size 4 to store coordinates of a shape (square/rectangle). 1st vector is for x and 2nd for y. To find out the area of the shape, I need the difference in their length. How do I find the difference between 2 elements within the same vector? Using square as an example:

vector<int> x(4);
vector<int> y(4);

double Square::computeArea()
{
    int length;
    double area;

    if (x[0] == x[1]) //x coordinates are the same
    {
        length = y[0] - y[1]; //difference in y coordinates to find the length, need help here
    }
    else if (x[1] == x[2]
    {
        length = y[1] - y[2];
    }
    else if ... //repeat

    area = length * length;
    if (area < 0) { area = -area; }
    setArea(area)
    return area;
}

If your rectangle has edges which are parallel to the axis, and the points are ordered clockwise (or counterclockwise), you can simply use the first and third element of the arrays:

int yedge, xedge;

xedge = abs(x[0] - x[2]);

if ( xedge == 0 ) //beware, this check works well only for ints!
     return area = 0.0;
else yedge = abs(y[0] - y[2]);

return area = xedge * yedge;

If you have more general convex quadrilaterals use something like this:

int dx20 = x[2] - x[0];
int dy10 = y[1] - y[0];
int dy20 = y[2] - y[0];
int dx10 = x[1] - x[0];
int dy30 = y[3] - y[0];
int dx30 = x[3] - x[0];

area = 0.5*abs(dx20*dy10-dy20*dx10);
area += 0.5*abs(dx20*dy30-dy20*dx30);

The beauty of C++ and OOP is that you can think more in terms of the problem than how to program it.

If I were in your place I would use std::pair to save the coordinates.

And have a class representing the rectangle.

I am using the distance between point 1 and 2 as length, and point 1 and 4 as width. It may not be the correct approach in all cases but it should show you have to go about programming your function.

using namespace std;

class Rectangle // Class Rectangle
{
public:
    Rectangle(vector<pair<double, double>> neWcoordinates);
    double computeArea();

private:
    vector<pair<double, double>> coordinates; 
};

double Rectangle::computeArea()
{
    double length = sqrt(pow(coordinates[0].first-coordinates[1].first,2)+pow(coordinates[0].second-coordinates[1].second,2)
        );
    double width = sqrt(pow(coordinates[0].first-coordinates[3].first,2)+pow(coordinates[0].second-coordinates[3].second,2));
    return length*width;
}

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