std::gslice_C++中文网

std::gslice 是标识 std::valarray 下标子集的选择器,以跨度和大小的多层集定义。 std::gslice 类型对象可用作 valarray 的 operator[] 所选择的下标,例如,表示为 valarray 的多维数组的列。

给定起始值 s 、跨度列表 i
j
及大小列表 d
j
,从这些值构造的 std::gslice 选择下标集 k
j
=s+Σ
j
(i
j
d
j
)
.

例如拥有始于下标 3 ,跨度为 {19,4,1} 长度为 {2,4,3} 的 gslice 生成下列坐标集:

3 + 0*19 + 0*4 + 0*1 = 3,
3 + 0*19 + 0*4 + 1*1 = 4,
3 + 0*19 + 0*4 + 2*1 = 5,
3 + 0*19 + 1*4 + 0*1 = 7,
3 + 0*19 + 1*4 + 1*1 = 8,
...
3 + 1*19 + 3*4 + 2*1 = 36

可以构造选择某些下标多于一次的 std::gslice 对象:若上述示例使用跨度 {1,1,1} ,则下标将是 {3, 4, 5, 4, 5, 6, ...} 。这种 gslice 只可用于 std::valarray::operator[] 的 const 版本的参数,否则行为未定义。

成员函数

构造通用切片
(公开成员函数)
返回切片的参数
(公开成员函数)

std::gslice::gslice

gslice()

gslice( std::size_t start, const std::valarray<std::size_t>& sizes,
                           const std::valarray<std::size_t>& strides );

gslice( const gslice& other );

构造新的通用切片。

2) 以参数 startsizesstrides 构造新切片。

3) 构造 other 的副本。

参数

start - 首元素的位置
sizes - 定义每个维度元素数量的数组
strides - 定义每个维度中前后元素间的位置差数的数组
other - 要复制的另一切片

示例

演示使用 gslice 定位 3D 数组的列

#include <iostream>
#include <valarray>
void test_print(std::valarray<int>& v, int rows, int cols, int planes)
{
    for(int r=0; r<rows; ++r) {
        for(int c=0; c<cols; ++c) {
            for(int z=0; z<planes; ++z)
                std::cout << v[r*cols*planes + c*planes + z] << ' ';
            std::cout << '\n';
        }
        std::cout << '\n';
    }
}
int main()
{
    std::valarray<int> v = // 3d 数组: 2 x 4 x 3 元素
    { 111,112,113 , 121,122,123 , 131,132,133 , 141,142,143,
      211,212,213 , 221,222,223 , 231,232,233 , 241,242,243};
    // int ar3d[2][4][3]
    std::cout << "Initial 2x4x3 array:\n";
    test_print(v, 2, 4, 3);
 
    // 更新两个平面第一列的每个值
    v[std::gslice(0, {2, 4}, {4*3, 3})] = 1; // 二层的一个 12 元素跨度
                                             // 然后是四层的二个 3 元素跨度
 
    // 从第一平面的第二列减去第三列的值
    v[std::gslice(1, {1, 4}, {4*3, 3})] -= v[std::gslice(2, {1, 4}, {4*3, 3})];
 
    std::cout << "After column operations: \n";
    test_print(v, 2, 4, 3);
}

输出:

Initial 2x4x3 array:
111 112 113
121 122 123
131 132 133
141 142 143
 
211 212 213
221 222 223
231 232 233
241 242 243
 
After column operations:
1 -1 113
1 -1 123
1 -1 133
1 -1 143
 
1 212 213
1 222 223
1 232 233
1 242 243

参阅