Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process several arrays in one range for? [duplicate]

Tags:

c++

arrays

c++11

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 operating the size of arrays, if I know for sure they are of the same lenght?

UPD I really like the @PavelDavydov solution. But could anyone please offer a standard lib only solution. C++11 contains pairs and tuples too.

for (auto pair : std::make_tuple(&arr, &arr2));
like image 845
NuPagadi Avatar asked Nov 30 '22 19:11

NuPagadi


2 Answers

#include <boost/range/combine.hpp>

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

Update: ok, if you want to do it without boost, you can implement a higher order function for that.

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 than use it like this:

loop_two(arr, arr1, [] (unsigned a, unsigned b) {
  cout << a << endl;
});
like image 75
Pavel Davydov Avatar answered Dec 03 '22 07:12

Pavel Davydov


#include <iterator>
//.. 

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

//.. 

auto it = std::begin( arr2 );

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

It would be better to use standard algorithm std::copy because its name says about your intention.

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

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

For arrays of arithmetic types you can use also C function memcpy

#include <cstring>

...

std::memcpy( arr2, arr, std::extent<decltype(arr)>::value * sizeof( unsigned ) );
like image 40
Vlad from Moscow Avatar answered Dec 03 '22 09:12

Vlad from Moscow