How to handle multiple arrays in the same range?

I want to copy an array using range for. Is it possible?

Something like (obviously not working)

unsigned arr[15] = {};
unsigned arr2[15];

for (auto i : arr, auto &j : arr2)
    j = i;

Or are there some other tricks to avoid working with array sizes if I know for sure that they are the same length?

UPD I really like @PavelDavydov's solution. But someone can offer a standard lib-only solution . C ++ 11 contains pairs and tuples.

for (auto pair : std::make_tuple(&arr, &arr2));
+4
source share
4 answers
#include <boost/range/combine.hpp>

for (const auto& pair : boost::combine(arr, arr2)) {
  cout << get<0>(pair) << endl;
}

Update: well, if you want to do this without promotion, you can implement a higher order function for it.

template <class T, unsigned long FirstLen, unsigned long SecondLen, class Pred> 
typename std::enable_if<FirstLen == SecondLen, void>::type loop_two(T (&first)[FirstLen], T (&second)[SecondLen], Pred pred) {
  for (unsigned long len = 0; len < FirstLen; ++len) {
    pred(first[len], second[len]);  
  }
}

and use it as follows:

loop_two(arr, arr1, [] (unsigned a, unsigned b) {
  cout << a << endl;
});
+10
#include <iterator>
//.. 

unsigned arr[15] = {};
unsigned arr2[15];

//.. 

auto it = std::begin( arr2 );

for ( unsigned x : arr ) *it++ = x;

std::copy, .

#include <algorithm>
#include <iterator>
//...

std::copy( std::begin( arr ), std::end( arr ), std::begin( arr2 ) );

C memcpy

#include <cstring>

...

std::memcpy( arr2, arr, std::extent<decltype(arr)>::value * sizeof( unsigned ) );
+5

, - zip, https://gitlab.com/redistd/redistd/blob/master/include/redi/zip.h ( Boost.Tuple)

#include <redi/zip.h>

int main()
{
  unsigned arr[15] = {};
  unsigned arr2[15];

  for (auto i : redi::zip(arr, arr2))
    i.get<1>() = i.get<0>();
}
+3

. std:: begin std:: end . :

for(auto it1 = std::begin(arr), it2 = std::begin(arr2); it1 != std::end(arr); ++it1,++it2)
 *it2 = *it1;

std: array std::vector "" . ++ 11!

+1

Source: https://habr.com/ru/post/1530964/


All Articles