An array is like a vector<var>, with some additional features added.
array a = array::make(1)(2)(3)(5)(10); // initialize an array array b = array::sequence(2,0,10.01); // create an array with stepsize 2, from 0 to 10 array c = split("first second third"); // initialize an array by splitting a string a[1] = 100; // indexing works like in C/C++ (0-based) for(a.setfirst(); a; ++a) // loop over an array: it has its own iterator { cout<<a()<<endl; // use the () operator to access the current element }
I more and more frequently
face the liminations of C++ as a scripting language, and wish I would
have written this software in perl for example. One example is the
lack of arbitrary-length array initialization. In order to overcome
this problem, the following method is implemented: an arbitrary-length
array can be created by appending the elements in () parentheses after
array::make:
array a = array::make(1)(3)(6);
some_func(array::make(1)(2), array::make(4)(5)(6));
Another way to create an array is splitting a string:
void f(var &v) { array a; split(v,a); // ... do whatever } f("one two three");
array a = array::sequence(stepsize, from, to);The array will start from 'from' (no surprise), and will stop at 'to', inclusive. Be aware of floating point problems, for example
double from = 1.342; double to = 3.2543; array::sequence((to-from)/7, from, to);may or may not finally contain to. The safest is to add a small number (a fraction of the stepsize) to 'to'.
The following method is provided to easily iterate over an array: an array has a built-in, own iterator, which stores the current position in the array. The current element can be accessed by the () operator, the iterator can be incremented or decremented by the ++ or -- operators, the validity of the iterator position (within range) can be tested with the 'bool' conversion.
for(array a=split("2 4 6 8"); a; ++a) { cerr<<a()<<endl; }
Use the sort_n() or sort_s() member functions to sort an array as numbers or strings
array a = split("filename1.dat filename2.dat filename3.dat"); a.replace(".dat",".eps");
array.h array.cc
Initialization: the static function
array::make(var)returns a reference to a (static) array initialized with the provided single value. In the statement
array::make(1)(2)the parenthesis operator is called on the returned array, which appends the given element to the array, and returns a reference to the array itself. In this way these parenthesis operators can be chained, the array is initialized to contain the provided values. Since at every occurence of this statement a reference to the same (static) array is returned, 2 or more such statements should not be provided as arguments to the same function call.