Any simple way to pull multiple elements from an array?

Say we have an array X with 100 elements.

To access elements 1, 3, and 5, in Matlab, I'd just enter:
y=X([1 3 5]);

Is there a built-in function in C++ to do that without using a for loop?

Obviously I tried

X[1 2] and such but the compiler gets angry.
Last edited on
Just

y = X[1];
y = X[3];
y = X[5];

When you're accessing elements in an array it needs an index to look at. So to access multiple values you need to have separate calls for each index.

2 5 8 12 11 1 3 <- Values
0 1 2 3 4 5 6 <- Index

Reference:
http://www.cplusplus.com/doc/tutorial/arrays/

I don't really understand the equation above. I'm guessing y is an array (maybe a vector?) of 3 and you are setting it to those three elements of the array X? If that's the case then you'd need to do something like:
1
2
3
y[0] = x[1]; 
y[1] = x[3]; 
y[2] = x[5];


Remember MATLAB m files are much higher level than C++. That means that many more things are done for you. Here, we are much closer to the processor and need to tell it every specific instruction.

You COULD make a class that would do something like this. But you'd have to define overloading functions and the syntax wouldn't be the same. It would be something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cstdarg>
class Array
{
  double X[100];
public:
  double* operator[] (int size, ...)
  {
    va_list vl;
    va_start(vl,size);
    double* y = new double[size];

    for (int i = 0; i < size; ++i)
      y[i]=X[ va_arg(vl,int) ];

    va_end(vl);
  }
};


This will create an array with those elements in it,. used like so:
1
2
3
4
double* y;
Array X;
// X gets populated somehow
y = X[3, 1, 3, 5];


The first argument represents the size of y. The rest of the arguments represent the indices of X that are being sent to y.

Note that if you don't use the delete keyword here, you'll have memory leaks.
Last edited on
Stebond, thanks that is very helpful.

You wrote:
"I don't really understand the equation above. I'm guessing y is an array (maybe a vector?) of 3 and you are setting it to those three elements of the array X?"

Yes, exactly.

Thanks for the help on what I'll need to do. I guess I need to get used to taking care of these kind of details, at least in making a class that does it which is a nice suggestion. Once I learn how to do classes :)
Last edited on
Topic archived. No new replies allowed.