Foreach for Int Array
9
I was coding a project that used arrays when the lack of a standard foreach in C/C++ got to me. So, I coded this little function to help me. It applies a function that returns int to each element of the array.
void foreach(int a[], int func(int n))
{
for(int i = (sizeof(a) / 4) - 1; i > -1; --i)
a[i] = func(a[i]);
}
#include <iostream.h>
int myprint(int i)
{
cout << i << endl;
return i;
}
int add1(int i)
{
return i + 1;
}
void main()
{
int arr = {0, 1, 2, 3};
foreach(arr, myprint);
foreach(arr, add1);
foreach(arr, myprint);
}






i.e. map_int, map_str, map_dbl, map_float, map_int_2d, et cetera.
By Jove, I do think you've inspired me!
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?
using namespace std;
#include <iostream>
#define foreach(arr,func) for( int i=0; i < sizeof(arr)/sizeof(arr[0]); i ++ ) arr[i] = func(arr[i]);
int myprint_i(int i)
{
cout << i << endl;
return i;
}
int main()
{
int arr[] = {0, 1, 2, 3};
foreach(arr, myprint);
}
#include
int arr = {0, 1, 2, 3};
for_each(arr, arr+4, print);
Oh, BTW, sizeof(int) is not necessarily 4. Welcome to the 64-bit world.
And also its easy for you to call sometihng "Bad," because you haven't submitted anything. Why don't you submit a little then we can see who has "bad" code.
(sizeof(a) / 4)
[/quote]
right there you say the size of int is 4 which is not right. you should do
(sizeof(a) / sizeof(int))
FURTHERMORE..... and this is very important. this code is completely worthless.
sizeof(a) will return the sizeof a pointer. that's because when you pass an array to a function that function sees the array only as a pointer back to a place on the stack. The code you provided doesn't even compile because of this line:
int arr = {0, 1, 2, 3};
should be
int arr[] = {0, 1, 2, 3};
in the end how hard is it to type:
int i;
for (i = 0; i < (sizeof(a)/sizeof(int); i++)
{
}
if you actually wanted a foreach loop write a macro.
did you test this code at all. no matter how many items I put in a[] it always prints
0
1
I don't know why everyone rated this code good other than they must not know C very well.