我正在寻找一种将矢量的所有元素转换为cv::Point
或其他用户定义的结构类型的良好且现代的方法:
struct ColorSpacePoint
{
int X;
int Y;
}
struct NewColorSpacePoint
{
int X;
int Y;
}
std::vector<ColorSpacePoint> points{ColorSpacePoint{2,3}, ColorSpacePoint{9,6}};
std::vector<NewColorSpacePoint> = ...
std::vector<cv::Point> = ...
答案 0 :(得分:3)
您可以将转化运算符添加到ColorSpacePoint
:
struct ColorSpacePoint
{
int X;
int Y;
operator NewColorSpacePoint() { return {X,Y}; }
};
或NewColorSpacePoint
的非显式构造函数:
struct NewColorSpacePoint
{
int X;
int Y;
NewColorSpacePoint (const ColorSpacePoint& rhs) : X{rhs.X}, Y{rhs.Y} {}
};
这样您就可以使用std::vector
范围构造函数:
std::vector<NewColorSpacePoint> new_points {points.begin(), points.end()};
如果您不想使用隐式转换,您可以创建一个免费功能并使用std::transform
:
NewColorSpacePoint to_new_color (const ColorSpacePoint& csp) {
return {csp.X,csp.Y};
}
std::vector<NewColorSpacePoint> new_points;
new_points.reserve(points.size());
std::transform(points.begin(), points.end(),
std::back_inserter(new_points), to_new_color);
答案 1 :(得分:1)
将转化运算符从$_GET['name']
添加到ColorSpacePoint
和NewColorSpacePoint
,例如:
cv::Point
然后使用struct NewColorSpacePoint
{
int X;
int Y;
};
struct ColorSpacePoint
{
int X;
int Y;
operator NewColorSpacePoint() { return {X, Y}; }
};
std::vector
,它将一系列迭代器作为参数:
std::vector<ColorSpacePoint> points{ColorSpacePoint{2,3}, ColorSpacePoint{9,6}};
std::vector<NewColorSpacePoint> new_points(points.begin(), points.end());
或使用constructor:
std::vector<NewColorSpacePoint> new_points;
new_points.insert(new_points.end(), points.begin(), points.end());