-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvslice.cpp
54 lines (49 loc) · 1 KB
/
vslice.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// vslice.cpp -- using valarray slices
#include <iostream>
#include <valarray>
#include <cstdlib>
const int SIZE = 12;
typedef std::valarray<int> vint;
void show(const vint & v, int cols);
int main()
{
using std::slice;
using std::cout;
vint valint(SIZE);
int i;
for (i = 0; i < SIZE; ++i) {
valint[i] = std::rand() % 10;
}
cout << "Original array:\n";
show(valint, 3);
vint vcol(valint[slice(1,4,3)]);
cout << "Second column:\n";
show(vcol, 1);
vint vrow(valint[slice(3,3,1)]);
cout << "Second row:\n";
show(vrow, 3);
valint[slice(2,4,3)] = 10;
cout << "Set first column to sum of next two:\n";
valint[slice(0,4,3)] = vint(valint[slice(1,4,3)])
+ vint(valint[slice(2,4,3)]);
show(valint, 3);
return 0;
}
void show(const vint & v, int cols)
{
using std::cout;
using std::endl;
int lim = v.size();
for (int i = 0; i < lim; ++i) {
cout.width(3);
cout << v[i];
if (i % cols == cols - 1) {
cout << endl;
} else {
cout << ' ';
}
if (lim % cols != 0) {
cout << endl;
}
}
}