Sign in to follow this  
silvermace

std::for_each on standard C++ array works?

Recommended Posts

silvermace    634
I honestly expected some kind of "non-container type" error.. but this compiles and runs on VC++ 2005 and g++ 3.4.2 (mingw) Is this allowed (see: good form/practice) ? I mean, it's cool if it isn't and it's cool if it is... but anyone know for sure? (I've google'd and all the examples I find use std::vector's)
#include <iostream>
#include <algorithm>

class A 
{
private:
	long x;
public:
	void set(long x) { this->x = x; }
	const long get() const { return this->x; }
};

struct functor {
	void operator()(A& vs) const 
		{ std::cout << vs.get() << ", "; }
};

int main()
{	
	A* ar = new A[32];
	for(int i=0; i<32; i++ )
		ar[i].set((long)((i+1)*(i+1)));
	
	std::for_each( ar, ar + 32, functor() );

	delete [] ar;
	return 0;
} 




produces the expected output: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, which is interesting. g++ -W -Wall test.cc -otest no warnings, no errors. cl /EHsc test.cc no warnings, no errors.

Share this post


Link to post
Share on other sites
0xFFFF0000    163
The standard says it all really.

Quote:

Since iterators are an abstraction of pointers, their semantics is a generalization of most of the semantics of pointers in C + +. This ensures that every function template that takes iterators works as well with regular pointers.



The algorithms will make use of the iterator_traits template which has a specialization for pointers.

Share this post


Link to post
Share on other sites
Zahlman    1682
It's perfectly good form (at least insofar as using the array in the first place is good form ;) ) and the library is specifically designed to make sure this sort of thing works. :)

Share this post


Link to post
Share on other sites
silvermace    634
thats eff'ing brilliant [smile], and yep Zahlman I appreciate the fact that the array should actually be a container anyway, this was just some random experimentation.

Thanks for the replies, Rateage++

-Danu

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this