如何在 C++ 中从 ROS 正确发送数组?

How do you properly send an array from ROS in C++?

我正在使用 Kinetic。

我有一条自定义消息path.msg

string path_name
segment[] segments

我正在尝试使用该消息类型发送 ROS 目标。

我在我的代码中初始化了一个数组

cuarl_rover_planner::segment segments[path->getSegments().size()];
//do stuff that populates the array
cuarl_rover_planner::path action_path;
action_path.segments = segments; // Error here

我收到这个错误

error: no match for ‘operator=’ (operand types are ‘cuarl_rover_planner::path_<std::allocator<void> >::_segments_type {aka std::vector<cuarl_rover_planner::segment_<std::allocator<void> >, std::allocator<cuarl_rover_planner::segment_<std::allocator<void> > > >}’ and ‘cuarl_rover_planner::segment [(<anonymous> + 1)] {aka cuarl_rover_planner::segment_<std::allocator<void> > [(<anonymous> + 1)]}’)
         action_path.segments = segments;

我假设 action_path.segments 采用不同的数据类型,但我从该错误消息中不明白该数据类型是什么。

action_path.segments 是一个 std::vector<segment>,但是您的 segments 变量只是一个片段,而不是片段向量。如果只想添加一个段,可以使用action_path.push_back(segment)。否则,您可以将 segments 声明为

std::vector<cuarl_rover_planner::segment> segments(path->getSegments().size());

如果你出于某种原因想要使用原始指针数组(就像你可能在这里),你必须首先明确地将其设置为 std::vector,即

action_path.segments = std::vector<cuarl_rover_planner::segment>(segments, segments+path->getSegments().size());

有关从原始 C 数组设置向量的更多信息,请参阅 How to initialize std::vector from C-style array?