Passing an array with a struct to a function array argument

Started by
13 comments, last by ApochPiQ 12 years, 7 months ago
*sigh*

No.



#include <vector>

struct SomeStuff
{
int WholeNumber;
float RealNumber;
bool Flag;
};

int main()
{
std::vector<SomeStuff> stuff;

// Call stuff.push_back() to load the vector up with data

std::vector<int> wholenums;
for(std::vector<SomeStuff>::const_iterator iter = stuff.begin(); iter != stuff.end(); ++iter)
wholenums.push_back(iter->WholeNumber);
}



Or there's the C++11 solution which uses a lambda and std::for_each instead of a loop. Or maybe you could use C++03 std::for_each and pass a functor which does the job as well. Doesn't matter.

If you want to write your program in C++, write it in C++. Raw arrays are bad.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Advertisement
Ok now I get the error

error C2057: expected constant expression
with this code


const int size=physworld.maxobjs;
int i,temparr[size];



And why are raw arrays so bad?
If it hasn't exploded, I haven't touched it.
ApochPiQ, I agree that std::vector is probably a better choice here but if he don't even know how to pass an array it might be confusing to introduce a bunch of new functionality like templates, iterators, etc.

MadScientist , if you are ready. Look into what ApochPiQ said.

EDIT: you get an error because the array size needs to be a compile time constant. This is one of the disadvantages with raw arrays.
I'd just like to know why raw arrays are bad, i am willing at some point to learn vectors.
If it hasn't exploded, I haven't touched it.
Raw arrays are bad because they are incredibly brittle and subtle. Do you know how arrays decay to pointer types in C++? Do you know how to avoid type safety issues and code confusion when arrays do implicitly decay? Do you know what a conformant array is and how to use them? Do you know what happens if you access element 15 in an array that only has 10 elements? What if your program decides it needs more than the number of elements you originally put in the array?

None of that stuff matters if you use std::vector.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement