0

I have this code:

int a[4][4]=
{
   {1,2,3,4},
   {5,6,7,8},
   {9,10,11,12},
   {13,14,15,16}
}

And I want to initialize B which is defined as below:

vector<vector<int>> b;

I know that I can do this with two loops (and possibly with one loop as documented here: https://stackoverflow.com/a/4092996/654019

But is there any way that I can do this without any loop?

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
mans
  • 17,104
  • 45
  • 172
  • 321
  • You could do it with recursion, that would avoid any loops. Although it would be more inefficient than using loops. – Eljay Jul 26 '21 at 17:36
  • I'm not sure what you're specifically looking for. My attempt to do it without a (visible) loop: [demo on coliru](http://coliru.stacked-crooked.com/a/dc2cdf1fb5ad96e2) – Scheff's Cat Jul 26 '21 at 17:55
  • The data needs to be copied from the array to the `vector`, so whether you write it or not, there will be a loop, recursion or an unrolled loop somewhere to do the work. Suggestion: You can make a the job a bit easier by replacing the `vector` of `vector`s with a single `vector` [that LOOKS like it's 2D](https://stackoverflow.com/a/2076668/4581301). For small matrixes this is often much, much faster to use because all of the data is in one easily-cached block. – user4581301 Jul 26 '21 at 18:09
  • Here's how to initialize **b** without a loop: `auto b = vector>{ { a[0][0], a[0][1], a[0][2], a[0][3] }, { a[1][0], a[1][1], a[1][2], a[1][3] }, { a[2][0], a[2][1], a[2][2], a[2][3] }, { a[3][0], a[3][1], a[3][2], a[3][3] }, };` – Eljay Jul 26 '21 at 19:12
  • @Eljay Is this faster than using a loop? – mans Jul 26 '21 at 21:21
  • I haven't profiled it, so I'm not sure. At `-O3`, I expect it will be close to or exactly the same performance. – Eljay Jul 26 '21 at 21:22

1 Answers1

1

You could use for_each if you just want to avoid writing a loop and let the algorithm do it for you: https://godbolt.org/z/jxT8vfhPr

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    int a[4][4] = {
        {1,2,3,4},
        {5,6,7,8},
        {9,10,11,12},
        {13,14,15,16}
    };
    std::vector<std::vector<int>> b;

    std::for_each(a, a + 4, [&b](auto v){
        b.push_back(std::vector<int>(v, v + 4));
    });

    std::for_each(cbegin(b), cend(b), [&b](auto v) {
        std::copy(cbegin(v), cend(v), std::ostream_iterator<int>(std::cout, " "));
        std::cout << "\n";
    });
}
rturrado
  • 7,699
  • 6
  • 42
  • 62