首页 > 解决方案 > 如何在 C++ 中正确地从 ROS 发送数组?

问题描述

我正在使用动力学。

我有一条自定义消息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采用不同的数据类型,但从该错误消息中我不明白该数据类型是什么。

标签: c++ros

解决方案


action_path.segments是 a 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 样式数组初始化 std::vector?有关从原始 C 数组设置向量的更多信息。


推荐阅读