定义头文件:在cstdlib头文件中 三个参数start,number,stride:start表示选中的第一个元素的索引;number表示选中的数据个数;stride表示步进值 如何选中元素的:从start指向的元素开始作为第一个元素,start+n*stride选中第n的元素,直到选中number个元素 应用:使用一维valarray存储二维数组
代码
/* Project name : _30slice Last modified Date: 2022年4月20日10点28分 Last Version: V1.0 Descriptions: 切片操作 */ /* slice类:定义头文件:在cstdlib头文件中三个参数start,number,stride:start表示选中的第一个元素的索引;number表示选中的数据个数;stride表示步进值如何选中元素的:从start指向的元素开始作为第一个元素,start+n*stride选中第n的元素,直到选中number个元素应用:使用一维valarray存储二维数组 */ #include#include #include const int SIZE = 12; typedef std::valarray vint; // simplify declarations void show(const vint& v, int cols); int main() {using std::slice; // from using std::cout;vint valint(SIZE); // think of as 4 rows of 3int i;for (i = 0; i < SIZE; ++i)valint[i] = std::rand() % 10;cout << "Original array:\n";show(valint, 3); // show in 3 columnsvint vcol(valint[slice(1, 4, 3)]); // extract 2nd columncout << "Second column:\n";show(vcol, 1); // show in 1 columnvint vrow(valint[slice(3, 3, 1)]); // extract 2nd rowcout << "Second row:\n";show(vrow, 3);valint[slice(2, 4, 3)] = 10; // assign to 2nd columncout << "Set last column to 10:\n";show(valint, 3);cout << "Set first column to sum of next two:\n";// + not defined for slices, so convert to valarray valint[slice(0, 4, 3)] = vint(valint[slice(1, 4, 3)])+ vint(valint[slice(2, 4, 3)]);//为什么要加vint(),是因为slice()没有重载+操作符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;elsecout << ' ';}if (lim % cols != 0)cout << endl; }
运行结果
Original array:1 7 40 9 48 8 24 5 5 Second column:7985 Second row:0 9 4 Set last column to 10:1 7 100 9 108 8 104 5 10 Set first column to sum of next two:17 7 1019 9 1018 8 1015 5 10 D:\Prj\_C++Self\_30slice\x64\Debug\_30slice.exe (进程 2604)已退出,代码为 0。 要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。 按任意键关闭此窗口. . .
上一篇:借月抒情,思念家乡和亲人的诗句:
下一篇:实现一个通用的函数柯里化的函数