'Treating an array of structs containing `x` as an array of `x`
Suppose I have an array a of struct S that includes member x.
I also have a function f that accepts an array of x (without the struct).
//file1
struct S {
int x;
//other members...
};
S s[1000];
//file2
void f(int x[]);
I could modify f to accept an array of S, but this pattern is making my code less modular as I have to propagate the definiton of S, and making my functions less generic. I could loop over a and copy each x to a new array, but a might be large. Is there a way to keep modularity and efficiency?
For instance, maybe f could also accept the size of the struct and use it for pointer arithmetic, therefore treating an array of arbitrary structs that contain x as an actual array of x?
Solution 1:[1]
Is there a way to keep modularity and efficiency?
There is a way: Templates.
Since modifying f seems to be an option, you can achieve your goal by making it a function template. It could accept any range of integers. You can then adapt the array of S to pass it into f.
Example:
template<class Range>
void f(Range&& x);
// usage
void example()
{
// using with s
auto s_to_int = [](S s) { return s.x; };
f(std::views::all(s) | std::views::transform(s_to_int));
// using with an array of integers
int arr[] = {1, 2, 3};
f(arr);
}
S contains a timestamp and datapoint, and f is a component of a Discrete Fourier Transform that operates a vector of datapoints.
If you're going to do numerical operations on the array of S, then this seems inefficient.
You're likely better off by using an array of data points, and a separate array of timestamps where the indices of each array correspond to each other.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
