0

I would like to access the second element of ROS-Message message_a.

# ROS-Message message_a
Header header
message_b[] test

ROS-Message 1 contains ROS-Message 2!

# ROS-Message message_b
Header header
uint32[] result

In my main code I loop with a for-each loop through the message test with the datatyp message_a.

for ( message_a::Test1 test : message_a.message_b ) {
  uint32_t c = test.result;
}

How can I access for example the second element of message_b? I need that because I want to get the result of the second test.

With the for-each loop that you see above, it will loop through all elements of message_b. How can I change this for-each loop to a general for-loop? Then I could just loop from 2 to 3...

Tik0
  • 2,499
  • 4
  • 35
  • 50
marv
  • 1
  • 1
  • Your question is confusing. Do you want the second result of all tests, the second result of the second test, or all results of the second test? – Tik0 Sep 05 '18 at 16:59

2 Answers2

0

You can change the range-based (aka for-each) loop to an index based for loop like this which iterates over the second, third, ..., and final result of test 42:

std::size_t test_idx      = 42; // Second element of results
std::size_t result_start  = 1; // start from the second result
std::size_t result_end    = your_msg_obj.test.at(test_idx).size(); // run until end of all in the given test

// For loop that iterates over all results in a given test
for ( std::size_t result_idx = result_start; idx < result_end; ++idx ) {
  uint32_t c = your_msg_obj.test.at(test_idx).result.at(result_idx);
  // ... fancy stuff
}
Tik0
  • 2,499
  • 4
  • 35
  • 50
0

The ROS documentatation of messages explains that array message fields are generated as std::vector in C++. In your case the field test is of type std::vector<message_b>, result of type std::vector<uint32_t>.

C++ vectors can be accessed in serval ways, you can find them in in this answer. In your case simply accessing the items by index should be possible like:

for(size_t i = 0; i != your_message_a.test.size(); i++)
{
    //Access the second result item of each test item
    uint32_t c = your_message_a.test[i].result[1];
}
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49