简体   繁体   English

C ++计算向量中两个元素之间的差

[英]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). 我有2个大小为4的向量来存储形状(正方形/矩形)的坐标。 1st vector is for x and 2nd for y. 第一个向量用于x,第二个向量用于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? 如何找到同一向量中2个元素之间的差异? Using square as an example: 以square为例:

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. C ++和OOP的优点在于,您可以从问题的角度思考而不是如何编程。

If I were in your place I would use std::pair to save the coordinates. 如果我在您的位置,则可以使用std :: pair保存坐标。

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. 我将点1和2之间的距离用作长度,将点1和4之间的距离用作宽度。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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