C++ slice类

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。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jasmine-Lily

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值