C++/Data Structure/Valarray
Demonstrate gslice() in valarray
#include <iostream>
#include <valarray>
using namespace std;
int main()
{
valarray<int> valarrayObject(12), result;
valarray<size_t> len(2), interval(2);
unsigned int i;
for(i = 0; i < 12; i++)
valarrayObject[ i ] = i;
len[0] = 3;
len[1] = 3;
interval[0] = 2;
interval[1] = 3;
cout << "Contents of valarrayObject: ";
for(i = 0; i <12; i++)
cout << valarrayObject[i] << " ";
cout << endl;
result = valarrayObject[gslice(0,len,interval)];
cout << "Contents of result: ";
for(i = 0; i < result.size(); i++)
cout << result[i] << " ";
return 0;
}
Demonstrate slice
#include <iostream>
#include <valarray>
using namespace std;
int main()
{
valarray<int> valarrayObject(10), result;
unsigned int i;
for(i = 0; i < 10; i++)
valarrayObject[ i ] = i;
cout << "Contents of valarrayObject: ";
for(i = 0; i <10; i++)
cout << valarrayObject[ i ] << " ";
cout << endl;
result = valarrayObject[slice(0, 5, 2)];
cout << "Contents of result: ";
for(i = 0; i < result.size(); i++)
cout << result[ i ] << " ";
return 0;
}
Demonstrate valarray: assign value,
#include <iostream>
#include <valarray>
#include <cmath>
using namespace std;
int main()
{
valarray<int> valarrayObject(10);
int i;
for(i = 0; i <10; i++)
valarrayObject[ i ] = i;
cout << "Original contents: ";
for(i = 0; i <10; i++)
cout << valarrayObject[i] << " ";
cout << endl;
valarrayObject = valarrayObject.cshift(3);
cout << "Shifted contents: ";
for(i = 0; i <10; i++)
cout << valarrayObject[i] << " ";
cout << endl;
valarray<bool> valarrayObject2 = valarrayObject < 5;
cout << "Those elements less than 5: ";
for(i = 0; i <10; i++)
cout << valarrayObject2[i] << " ";
cout << endl << endl;
valarray<double> valarrayObject3(5);
for(i = 0; i <5; i++)
valarrayObject3[i] = (double) i;
cout << "Original contents: ";
for(i = 0; i <5; i++)
cout << valarrayObject3[i] << " ";
cout << endl;
valarrayObject3 = sqrt(valarrayObject3);
cout << "Square roots: ";
for(i = 0; i <5; i++)
cout << valarrayObject3[i] << " ";
cout << endl;
valarrayObject3 = valarrayObject3 + valarrayObject3;
cout << "Double the square roots: ";
for(i = 0; i <5; i++)
cout << valarrayObject3[i] << " ";
cout << endl;
valarrayObject3 = valarrayObject3 - 10.0;
cout << "After subtracting 10 from each element:\n";
for(i = 0; i <5; i++)
cout << valarrayObject3[i] << " ";
cout << endl;
return 0;
}