vslice.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // vslice.cpp -- using valarray slices
  2. #include <iostream>
  3. #include <valarray>
  4. #include <cstdlib>
  5. const int SIZE = 12;
  6. typedef std::valarray<int> vint; // simplify declarations
  7. void show(const vint & v, int cols);
  8. int main()
  9. {
  10. using std::slice; // from <valarray>
  11. using std::cout;
  12. vint valint(SIZE); // think of as 4 rows of 3
  13. int i;
  14. for (i = 0; i < SIZE; ++i)
  15. valint[i] = std::rand() % 10;
  16. cout << "Original array:\n";
  17. show(valint, 3); // show in 3 columns
  18. vint vcol(valint[slice(1,4,3)]); // extract 2nd column
  19. cout << "Second column:\n";
  20. show(vcol, 1); // show in 1 column
  21. vint vrow(valint[slice(3,3,1)]); // extract 2nd row
  22. cout << "Second row:\n";
  23. show(vrow, 3);
  24. valint[slice(2,4,3)] = 10; // assign to 2nd column
  25. cout << "Set last column to 10:\n";
  26. show(valint, 3);
  27. cout << "Set first column to sum of next two:\n";
  28. // + not defined for slices, so convert to valarray<int>
  29. valint[slice(0,4,3)] = vint(valint[slice(1,4,3)])
  30. + vint(valint[slice(2,4,3)]);
  31. show(valint, 3);
  32. // std::cin.get();
  33. return 0;
  34. }
  35. void show(const vint & v, int cols)
  36. {
  37. using std::cout;
  38. using std::endl;
  39. int lim = v.size();
  40. for (int i = 0; i < lim; ++i)
  41. {
  42. cout.width(3);
  43. cout << v[i];
  44. if (i % cols == cols - 1)
  45. cout << endl;
  46. else
  47. cout << ' ';
  48. }
  49. if (lim % cols != 0)
  50. cout << endl;
  51. }