简体   繁体   English

减去两个向量 <point2f> 直

[英]Subtracting two vector<point2f> directly

I have to subtract two vectors of type Point2f (both are of same size). 我必须减去Point2f类型的两个向量(两个向量的大小相同)。 I know it can be done by extracting the values at each index and then subtracting them in a loop but is there a direct method to it? 我知道可以通过在每个索引中提取值然后在循环中减去它们来完成,但是有直接方法吗? Something like 就像是

Vector<Point2f> A[3];
A[2] = A[1] - A[0];

just for sports ;) 只是为了运动;)

std::vector<Point2f> A,B;
A.push_back(Point2f(1,2));
A.push_back(Point2f(3,4));
A.push_back(Point2f(5,6));
B.push_back(Point2f(5,2));
B.push_back(Point2f(4,4));
B.push_back(Point2f(3,6));

// Mat C; subtract(A,B,C);
Mat C = Mat(A) - Mat(B);
cout<< A << endl << B << endl <<C<<endl;



[1, 2;  3, 4;  5, 6]
[5, 2;  4, 4;  3, 6]
[-4, 0;  -1, 0;  2, 0]

As per the documentation link that you provided, subtraction of two points is supported. 根据您提供的文档链接,支持两点相减。 So the following should work: 因此,以下应该工作:

std::transform (A[1].begin(), A[1].end(), A[0].begin(), A[2].begin(), std::minus<Point2f>());

Note that this assumes that A[2] is big enough to store the result. 请注意,这假设A [2]足以存储结果。

Alternative, you could write your own overloaded operator-() for vector subtraction: 或者,您可以编写自己的重载operator-()进行矢量减法:

const vector<Point2f> operator-(const vector<Point2f>& lhs, const vector<Point2f>& rhs)
{ ... }

You would need to optimize the above function to avoid a copy of the vector when the function returns. 您需要优化上面的函数,以避免在函数返回时复制向量。 This does not preclude the need to write the looping code that you want to avoid. 这并不排除需要编写要避免的循环代码的必要。 But it will give you a cleaner syntax for vector subtractions. 但是它将为您提供用于向量减法的更简洁的语法。

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

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