[英]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.