如何找到2个线段C ++之间的交点坐标

时间:2014-03-03 10:21:28

标签: c++

我是c ++编程语言的新手,我只需要知道如何根据开始和结束点声明一组线段?在C ++中有类似的东西吗? 我有这个代码从文本文件中读取线段的起点和终点,并将输入分为4个向量:X_start,Y_start,X_end,Y_end。 我需要知道如何使用这些向量来定义线段?任何帮助,将不胜感激。提前致谢

#include <iostream>
#include <algorithm> // for std::copy#include <iostream>
#include <iterator>
#include <fstream>
#include <math.h>
#include <vector>
#include <algorithm> // for std::copy
using namespace std;

int main()
{
std::ifstream is("D:\\Task1.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::vector<double> X_start(start, end);
std::vector<double> Y_start(start, end);
std::vector<double> X_end(start, end);
std::vector<double> Y_end(start, end);
std::vector<double>::iterator i;
std::vector<double>::iterator j;
float left, top, right, bottom; // Bounding Box For Line Segments
left = 12;
top = 12;
right = 0;
bottom = 0;

std::cout << "Read " << numbers.size() << " numbers" << std::endl;
std::copy(numbers.begin(), numbers.end(), 
        std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;

for (vector<double>::iterator i = numbers.begin();
                       i != numbers.end();
                       ++i)
{
for(int j = 0; j < numbers.size(); j = j+4)
{
std::cout << "elemnts of X_start " << numbers[j] << "  " <<std::endl;
X_start.push_back(numbers[j]);

}
for(int k = 1; k < numbers.size(); k = k+4)
{
std::cout << "elemnts of Y_start " << numbers[k] << " " <<std::endl;
Y_start.push_back(numbers[k]);
}
for(int l = 2; l < numbers.size(); l = l+4)
{
std::cout << "elemnts of X_end " << numbers[l] << " " <<std::endl;
X_end.push_back(numbers[l]);
}
for(int m = 3; m < numbers.size(); m = m+4)
{
std::cout << "elemnts of Y_end " << numbers[m] << " " <<std::endl;
Y_end.push_back(numbers[m]);
}
getchar();
}   
}

2 个答案:

答案 0 :(得分:0)

我使用以下功能。只需修改它即可满足您的要求。

class Point
{
    public:
    float x,y;
};


class LineSegment
{
    public:
    Point top;
    Point bottom;
};

Point* getIntersectionPoint(LineSegment line1,LineSegment line2)
{
    float s1_x, s1_y, s2_x, s2_y;
    float p1_x = line1.bottom.x,p1_y = line1.bottom.y;
    float p0_x = line1.top.x,p0_y = line1.top.y;
    float p3_x = line2.bottom.x,p3_y = line2.bottom.y;
    float p2_x = line2.top.x,p2_y = line2.top.y;
    s1_x = p1_x - p0_x;     s1_y = p1_y - p0_y;
    s2_x = p3_x - p2_x;     s2_y = p3_y - p2_y;

    float s, t;
    s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
    t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        Point *intsPoint = (Point *)malloc(sizeof(Point));
        intsPoint->x = p0_x + (t * s1_x);
        intsPoint->y = p0_y + (t * s1_y);
        return intsPoint;
    }

    return NULL;
}

答案 1 :(得分:0)

“我对c ++编程语言很陌生”

C ++有多新鲜?你是否理解你想要先做的事情所涉及的数学?

相关问题