#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.set((long)((i+1)*(i+1)));
std::for_each( ar, ar + 32, functor() );
delete [] ar;
return 0;
}
std::for_each on standard C++ array works?
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)
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.
The standard says it all really.
The algorithms will make use of the iterator_traits template which has a specialization for pointers.
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.
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. :)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement