簡體   English   中英

C ++計算向量中兩個元素之間的差

[英]C++ calculate difference between two elements in a vector

我有2個大小為4的向量來存儲形狀(正方形/矩形)的坐標。 第一個向量用於x,第二個向量用於y。 為了找出形狀的區域,我需要長度上的差異。 如何找到同一向量中2個元素之間的差異? 以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;
}

如果矩形的邊緣與軸平行,並且這些點按順時針(或逆時針)順序排列,則可以簡單地使用數組的第一個和第三個元素:

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;

如果您有更一般的凸四邊形,請使用以下方法:

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);

C ++和OOP的優點在於,您可以從問題的角度思考而不是如何編程。

如果我在您的位置,則可以使用std :: pair保存坐標。

並有一個代表矩形的類。

我將點1和2之間的距離用作長度,將點1和4之間的距離用作寬度。 在所有情況下,它可能都不是正確的方法,但它應該表明您必須開始編寫函數。

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