Oleg Oleg - 26 days ago 8
C++ Question

Get sparse subset of array as references

Is it possible to get a sparse (non-contiguous) subset of references to array elements?

Suppose I have array

a = [1,4,5]
and indices
pos = [0,1]
. I would like to get
b = [1,5]
without copying elements from
a
. In other words, I would like to slice into
a
and create a view called
b
.

The following errors since "expression is not assignable":

#include <array>

int main() {
std::array<double,3> a = {1, 4, 5};
std::array<double, 2> b;
int c = 0;
int pos[2] = {0,2};
for (auto i = a.begin(); i != a.end(); i++) {
&b[c] = i;
i++;
}
return 0;
}

Answer

You can't have direct references in a container. However, if you have access to C++11 you can use std::reference_wrapper:

#include <iostream>
#include <functional>
#include <vector>
#include <array>

int main() {
  std::array<double,3> a = {1, 4, 5};
  std::vector<std::reference_wrapper<double>> b;
  int pos[2] = {0,2};
  for (unsigned int i = 0; i < sizeof(pos) / sizeof(pos[0]); ++i) 
  {
      b.emplace_back(a[pos[i]]);
  }

  for(const auto& viewer: b)
  {
      std::cout << viewer << "\n";
  }
}

Otherwise, just use double*.

Comments