• Advertisement
Sign in to follow this  

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

This topic is 3958 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
Sign in to follow this  

  • Advertisement