使用标准库切片

时间:2016-04-13 21:00:03

标签: c++ c++14 slice valarray

标准库中是否有功能允许我切片std::slice或者我需要编写类似

的内容
std::slice refine(std::slice const& first, std::slice const& second)
{
    return {
        first.start() + second.start() * first.stride(),
        second.size(),
        first.stride() * second.stride()
    };
}

由我自己?

1 个答案:

答案 0 :(得分:0)

据我所知,标准库中没有这样的东西。

http://en.cppreference.com/w/cpp/numeric/valarray/slice

http://en.cppreference.com/w/cpp/numeric/valarray/slice_array

但是如果你使用的是const std :: valarray,你可以使用运算符

valarray<T> operator[] (slice slc) const;

将返回另一个std :: valarray,并且你可以再次应用std :: slice。

// slice example
#include <iostream>  // std::cout
#include <cstddef>   // std::size_t
#include <valarray>  // std::valarray, std::slice

int main() {
    std::valarray<int> foo(100);
    for (int i = 0; i < 100; ++i) foo[i] = i;

    std::valarray<int> bar = foo[std::slice(2, 20, 4)];

    std::cout << "slice(2,20,4):";
    for (auto b : bar) std::cout << ' ' << b;
    std::cout << '\n';

    auto const cfoo = foo;
    std::valarray<int> baz = cfoo[std::slice(2, 20, 4)][std::slice(3, 3, 3)];

    std::cout << "slice(3,3,3):";
    for (auto b : baz) std::cout << ' ' << b;
    std::cout << '\n';
    return 0;
}