0

I have a C-array like this:

int X[]={0, 1, 2, 3, 4, 5, 6, 7, 8};

I need to create two stl vectors out of this array, by means of slicing, possibly sharing the highest amount of memory and making less deep copies possible. The first vector Y must contain only the 0-th and first element each three elements, for example in this case this new vector Y will contain

std::vector<int> Y; // contains: [0,1,3,4,6,7]

and another vector Z must contain each 3rd element in the original array:

std::vector<int> Z; // contains [2,5,8]

A first solution based on for loops with copy is the following:

vector<int> Y,Z;
for (int i=0; i<9;i+=3)
{
    Y.push_back(*(X+i));
    Y.push_back(*(X+i+1));
    Z.push_back(*(X+2));
}

but I'm pretty sure that by means of custom iterators the problem could have a more efficient solution. Is there, anyway, some other faster version of implementing a mask-view on this array that avoid generating copies?

linello
  • 8,451
  • 18
  • 63
  • 109

2 Answers2

1

Do you maybe mean something like this:

#include <iostream>
#include <vector>
using namespace std;

struct MyIndexing {
    int* original;
    MyIndexing(int* o) : original(o) {}
    int& getY(int index){ return original[0]; /* to be done... */ }
    int& getZ(int index){ return original[(index+1)*3 -1]; }
};

int main() {
    int X[]={0, 1, 2, 3, 4, 5, 6, 7, 8};
    MyIndexing mi(X);
    for (int i=0;i<3;i++){ std::cout << mi.getZ(i) << " "; }
    return 0;
}

Prints:

2  5  8

It does not create vectors, but anyhow your requirements are a bit contradicting. Either you avoid copies or you create new vectors. Both isnt possible.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

If you HAVE to create vectors, you MUST make a copy of the data, as the vectors data is contiguous.

If you don't need the vectors, you could create 2 interfaces (forgive my C# terminology, but I think it's applicable), one that would provide a getter for Y data, one that would offer for X data; the implementation, extending these 2 interfaces can then hide the fact that your data is in a vector at all.

UKMonkey
  • 6,941
  • 3
  • 21
  • 30
  • All factually true. However, such an interface would be quite inefficient to use in most scenarios I'm imagining. Still, that does appear to be what the OP is (now) asking for, post-edit. You didn't really provide a solution though – Lightness Races in Orbit Oct 04 '16 at 14:30