【问题标题】:Initialization of a Boost point C++Boost 点 C++ 的初始化
【发布时间】:2018-06-04 07:52:40
【问题描述】:

我正在使用 Boost 库来操作 N 维域中的点。问题是如果不单独设置每个坐标,我找不到初始化它们的方法。

要获取或设置此库的坐标,应使用:

bg::model::point<double, 2, bg::cs::cartesian> point1; // Declaration
point1.set<0>(1.0);                                    // Coordinate 0 set 
point1.set<1>(2.0);                                    // Coordinate 1 set
double x = point1.get<0>();                            // Coordinate 0 get
double y = point1.get<1>();                            // Coordinate 1 get

您可以在https://www.boost.org/doc/libs/1_67_0/libs/geometry/doc/html/geometry/reference/models/model_point.html找到示例和信息

但是,我使用 N > 100 的 N 维空间中的点,我无法手动为每个坐标编写一行代码。但是这样的事情:

bg::model::point<double, 2, bg::cs::cartesian> point1;
for(int i(0); i<NDIM; ++i){
    point1.set<i>(1.0);
}

不起作用,因为坐标的索引需要是 const 值。你能帮我找到一种自动初始化坐标的方法吗?我尝试了很多东西,没有任何效果!

【问题讨论】:

标签: c++ boost constants boost-geometry


【解决方案1】:

您可以使用可变参数模板和std::index_sequenceNDIM 推导出索引并使用解包语法一起处理:

template <class Point, size_t... I>
void init(Point& p, std::index_sequence<I...>)
{
    int dummy[] = { (p.set<I>(1.0), 0)... };
    (void)dummy;
}

语法(void_func(), 0) 调用一个void 函数,但返回0。这是必要的,因为您不能将解包语法 ... 用于 void 函数。将它分配给一个数组并使用它(例如,将其转换为 void)确保没有任何东西被优化掉。

然后像这样调用这个函数:

init(point1, std::make_index_sequence<NDIM>());

注意NDIM 必须是const

有关index_sequence 工作原理的更多详细信息,请查看here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多