Simple(?) Array Manipulation

I'm struggling to find the answers to these simple questions.

1. Let's make a 1-D array:
 
float x[100];


Now, is there a way of performing operations on certain elements in the array.
eg. Can we set elements 15 to 25 to equal 7, say?

In a different language (IDL, which is fortran based) i would do something like:
 
x[14:24] = 7;   


but is there a way to do this in C++?

2. Then let's consider a 2-D array:
 
float y[100][100];


Is there a way to perform an operation on all the rows of a particular column (i may have got the column/row order mixed up, but hopefully you'll get what i mean). Again, i would have previously done something like:
1
2
3
4
5
6
7
8
9
10
11
y[10,*] = 7;

//i know this doesn't work, so i tried:

y[10][*] = 7;

//again, didn't work

y[10][];

//nor this 


So, is there a way of doing this?


jazpearson wrote:
is there a way of performing operations on certain elements in the array.
eg. Can we set elements 15 to 25 to equal 7, say?


To perform operations on all or some of the elements you need to loop through the entire array and perform the operations against whichever elements.
Last edited on
I'm going to contradict Return 0 a bit.

jazpearson wrote:
1. Let's make a 1-D array:

float x[100];

Now, is there a way of performing operations on certain elements in the array
eg. Can we set elements 15 to 25 to equal 7, say?


You can loop through (or address) a subset of an array using pointers and pointer arithmetic.

for (float* f = x + 15; f != x+26; ++f) *f = 7.0;

Or

std::fill(x+15, x+26, 7.0);
jazpearson wrote:
2. Then let's consider a 2-D array:


float y[100][100];



Is there a way to perform an operation on all the rows of a particular column (i may have got the column/row order mixed up, but hopefully you'll get what i mean). Again, i would have previously done something like:


We don't typically use C-style arrays much in C++. The C array operations are, as you are experiencing, a bit lacking. C++ doesn't extend the features of C arrays. Instead, C++ offers things like vector and valarray in the STL. And there are third-party libraries that make working with multi-dimensional arrays much easier. The Boost Multidimensional Array Library is one example.

http://www.boost.org/doc/libs/1_45_0/libs/multi_array/doc/user.html
http://www.cplusplus.com/reference/stl/vector/
http://www.cplusplus.com/reference/std/valarray/valarray/
Topic archived. No new replies allowed.