Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to iterate over two structures consecutively with a foreach loop

Is there an easy way to achieve this design pattern in c++17?

std::set<uint32_t> first;
std::set<uint32_t> second;

for (uint32_t number : JoinIterator<uint32_t>(first, second)) {
   <DO SOMETHING WITH number>
}

This would replace the following code:

std::set<uint32_t> first;
std::set<uint32_t> second;

for (uint32_t number : first) {
   <DO SOMETHING WITH number>
}

for (uint32_t number : second) {
   <DO SOMETHING WITH number>
}

All of the search results I have found are about looping over both structures in parallel, not looping over the structures consecutively.

like image 381
TheBat Avatar asked Mar 02 '23 17:03

TheBat


1 Answers

Use views::concat from range-v3:

for (uint32_t number : views::concat(first, second)) {
   <DO SOMETHING WITH number>
}

This only works with ranges that have the same underlying type (which is true in this example).


In Boost (i.e. range-v2), this is spelled boost::range::join(first, second).

Since it's not apparent from the Boost documentation directly, this function is found in boost/range/join.hpp

like image 194
Barry Avatar answered May 11 '23 02:05

Barry