449,017 Members | 1,004 Online
Need help? Post your question and get tips & solutions from a community of 449,017 IT Pros & Developers. It's quick & easy.

# valarray iterators?

 P: n/a Hello, I've did some some numerical programs in C/C++ before, but decided to use STL to write neater code. Then again I don't want to give up speed so I have a couple of questions. Apparently the recommended structure for a fast numeric code is valarray. Alas, from the sparse documentation in the books I looked into and a google search it appears that there are no iterators associated to them. I tried to "simulate" them with pointers but I am not sure if I am allowed to do so. Here is a basic example based on vector for calculating the first few factorials. //Example 1 #include #include #include #include using namespace std; const int MAX=10; vector v1(MAX), v2(v1); double gen_n() { static int i = 1; return i++; } int main() { generate(v1.begin(), v1.end(), gen_n); partial_sum(v1.begin(), v1.end(), v2.begin(), multiplies() ); ostream_iterator output(cout, " "); copy(v1.begin(), v1.end(), output); cout << endl; copy(v2.begin(), v2.end(), output); cout << endl; } // Example 2: same program with valarray instead of vector #include #include #include #include using namespace std; const int MAX = 10; valarray v1(MAX), v2(v1); double gen_n() { static int i = 1; return i++; } int main() { generate(&v1[0], &v1[MAX], gen_n); partial_sum(&v1[0], &v1[MAX], &v2[0], multiplies() ); ostream_iterator output(cout, " "); copy(&v1[0], &v1[MAX], output); cout << endl; copy(&v2[0], &v2[MAX], output); cout << endl; return 0; } When I compile it, I get the same correct result, but I wonder: 1. Can I use &v1[0] and the like instead of iterators? Will the second version run correctly on every platform/compiler, or just it so happens on my computer? 2. Running time: the above overly simplified code is very similar to something I run in a function zillion times. (MAX can be as high as 1000000, the generating function is much more complicated). Will the use of generate and partial_sum slow it down considerably and thus negating the reason for using valarray? I can always substitute them with loops, but then again I'll be back at the amorphous mess I had before. 3. Any further tips and caveats from professional number-crunchers and others are more than welcome. Thanks, Sanyi Jul 22 '05 #1