ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How to publish a vector< pair <int, int> >?

asked 2017-08-30 08:32:35 -0600

rosargh gravatar image

updated 2017-08-30 08:33:05 -0600

Hi,

I have created a vector of type pair < int, int >, and now I'm trying to publish it on a ROS topic. The size of the vector is already known. How can I proceed ?

I have tried:

    vector_pub = nh.advertise<std::vector<pair <int, int> > >("vector", 100);
    vector_pub.publish(vector_node_position);

but it doesn't compile. Could you please help me?

Thanks :)

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2017-08-30 09:38:43 -0600

Thomas D gravatar image

updated 2017-08-30 09:49:35 -0600

One way would be to create two custom messages, call them something like my_msgs/Pair.msg and my_msgs/VectorPair.msg. The contents would be:

my_msgs/Pair.msg

int a
int b

my_msgs/VectorPair.msg

my_msgs/Pair[] data

In your publishing node you would do:

#include <my_msgs/VectorPair.h>
vector_pub = nh.advertise<my_msgs::VectorPair>("vector", 100);
my_msgs Pair pair;
my_msgs::VectorPair vector_node_position;
pair.a = 1;
pair.b = 2;
vector_node_position.data.push_back(pair);
vector_pub.publish(vector_node_position);

Note that creating/populating the pair message and then pushing it into the vector message could happen inside a loop.

edit flag offensive delete link more

Comments

And if you'd like to avoid having to create the msg at the Publisher side, see ros/wiki/roscpp/MessageTraits. The Subscriber will still need the msg defs though.

gvdhoorn gravatar image gvdhoorn  ( 2017-08-30 10:17:04 -0600 )edit

Thank you Thomas D and gvdhoorn, I'll try this right away and come back for a feedback :)

rosargh gravatar image rosargh  ( 2017-08-31 01:58:11 -0600 )edit
0

answered 2017-08-31 09:22:47 -0600

rosargh gravatar image

I marked Thomas D's answer as the right one because I used it for reference, but if another newbie needs it, I think it's important to note that you have to change your CMakeLists.txt and package.xml :

In CMakeLists.txt:

find_package(catkin REQUIRED COMPONENTS ... message_generation ...)
...
add_message_files(
FILES
Pair.msg
VectorPair.msg
)
...
catkin_package(
INCLUDE_DIRS include
CATKIN_DEPENDS message_runtime
)
...
include_directories(include my_msg)
...
add_dependencies( your_executable ${PROJECT_NAME}_generate_messages_cpp )

And in package.xml:

 <build_depend>message_generation</build_depend> 
 <run_depend>message_runtime</run_depend>

Thank you so much for your help!

Cheers

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2017-08-30 08:32:35 -0600

Seen: 1,948 times

Last updated: Aug 31 '17