So i was working on some ros based UAV simulation and it just struck me when I had to initialize separate publishers for each UAV. Is it possible to make an array of such publishers and then reference them by just using their index number? I know I should just do it and try it, but I guessed asking here would be a faster option:)
Asked
Active
Viewed 817 times
1 Answers
0
Yes this is possible by collecting multiple ros::Publishers in containers. Here is a small example using an array:
#include <ros/ros.h>
#include <std_msgs/String.h>
int main(int argc, char *argv[])
{
ros::init(argc, argv, "test_node");
ros::NodeHandle nh;
ros::WallTimer timer;
//Create publishers
std::array<ros::Publisher, 3> publishers;
for (size_t i = 0; i < publishers.size(); i++)
{
std::stringstream topic_name;
topic_name << "topic" << i;
publishers[i] = nh.advertise<std_msgs::String>(topic_name.str(), 0);
}
//Publish
ros::Rate r(1);
std_msgs::String msg;
while (nh.ok())
{
std::stringstream message;
message << "Hello World " << ros::Time::now();
msg.data = message.str();
for (size_t i = 0; i < publishers.size(); i++)
{
publishers[i].publish(msg);
}
ros::spinOnce();
r.sleep();
}
return 0;
}
The node advertises the three topics
- /topic0
- /topic1
- /topic2
and publishes a simple string like Hello World 1562571209.130936883
with a rate of 1 Hz.

Fruchtzwerg
- 10,999
- 12
- 40
- 49