Answer to Question #250731 in C++ for hassi

Question #250731

Make a struct LINE include appropriate data members.

A line segment includes the endpoints, i.e. the points that it joins. 

structure should also provide a function to find the length of the Line 

Two lines can be compared to determine which line is shorter and vice versa. Provide function to compare two Lines 

Provide appropriate constructors for initialization.


1
Expert's answer
2021-10-13T06:25:10-0400
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;

struct Point {
    Point(double x=0, double y=0) : x(x), y(y) {}
    double x, y;
};


struct Line {
    Line(vector<Point> v) : joins(v) {}
    Line(Point a[], int size);
    Line(Point a, Point b);
    double length() const;


    vector<Point> joins;
};


Line::Line(Point a[], int size) {
    joins.resize(size);
    for (int i=0; i<size; i++) {
        joins[i] = a[i];
    }
}

Line::Line(Point a, Point b) {
    joins.resize(2);
    joins[0] = a;
    joins[1] = b;
}


double Line::length() const {
    double s = 0.0;
    for (int i=1; i<joins.size(); i++) {
        s += sqrt( (joins[i-1].x - joins[i].x) * (joins[i-1].x - joins[i].x) +
                   (joins[i-1].y - joins[i].y) * (joins[i-1].y - joins[i].y) );
    }
    return s;
}

inline bool operator<(const Line& l1, const Line& l2) {
    return l1.length() < l2.length();
}
inline bool operator==(const Line& l1, const Line& l2) {
    return l1.length() == l2.length();
}
inline bool operator<=(const Line& l1, const Line& l2) {
    return l1 < l2 || l1 == l2;
}
inline bool operator>(const Line& l1, const Line& l2) {
    return l2 < l1;
}
inline bool operator>=(const Line& l1, const Line& l2) {
    return l2 < l1 || l2 == l1;
}
inline bool operator!=(const Line& l1, const Line& l2) {
    return !(l1 == l2);
}

int main() {
    Point points[4] = {Point(0, 0), Point(1, 2), Point(2, -2), Point(3, 5)};
    Line l1(points, 4);
    Line l2(Point(0, 0), Point(3, 5));


    if (l1 < l2) {
        cout << "Line_1 is shorter than Line_2" << endl;
    }
    else { 
        cout << "Line_1 is not shorter than Line_2" << endl;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS