19 C++ slice类
19.1 简介
定义头文件:在cstdlib头文件中 三个参数start,number,stride:start表示选中的第一个元素的索引;number表示选中的数据个数;stride表示步进值 如何选中元素的:从start指向的元素开始作为第一个元素,start+n*stride选中第n的元素,直到选中number个元素 应用:使用一维valarray存储二维数组
19.2 举例
代码
/* 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 <iostream> #include <valarray> #include <cstdlib> const int SIZE = 12; typedef std::valarray<int> vint; // simplify declarations void show(const vint& v, int cols); int main() { using std::slice; // from <valarray> using std::cout; vint valint(SIZE); // think of as 4 rows of 3 int i; for (i = 0; i < SIZE; ++i) valint[i] = std::rand() % 10; cout << "Original array:\n"; show(valint, 3); // show in 3 columns vint vcol(valint[slice(1, 4, 3)]); // extract 2nd column cout << "Second column:\n"; show(vcol, 1); // show in 1 column vint vrow(valint[slice(3, 3, 1)]); // extract 2nd row cout << "Second row:\n"; show(vrow, 3); valint[slice(2, 4, 3)] = 10; // assign to 2nd column cout << "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<int> 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; else cout << ' '; } if (lim % cols != 0) cout << endl; }
运行结果
Original array: 1 7 4 0 9 4 8 8 2 4 5 5 Second column: 7 9 8 5 Second row: 0 9 4 Set last column to 10: 1 7 10 0 9 10 8 8 10 4 5 10 Set first column to sum of next two: 17 7 10 19 9 10 18 8 10 15 5 10 D:\Prj\_C++Self\_30slice\x64\Debug\_30slice.exe (进程 2604)已退出,代码为 0。 要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。 按任意键关闭此窗口. . .