【问题标题】:Slicing a slice using the Standard Library使用标准库切片
【发布时间】:2016-08-05 04:53:17
【问题描述】:

标准库中是否有允许我对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()
    };
}

我自己?

【问题讨论】:

  • 我应该提到我在用户定义的类中使用std::slice

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


【解决方案1】:

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

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;
}

【讨论】:

  • 我在用户定义的类中使用std::slice。顺便说一句,operator[](std::slice) conststd::valarray 中的坏处在于它通过复制 相应的元素来生成切片对象。如果std::valarray 很大,那么该操作将导致隐藏在优雅符号后面的严重性能损失。在我的课程中,我返回一个代理对象,其中包含对实际对象的引用。这就是std::valarrayoperator[](std::slice) 的非常量版本所做的。但是在那里,返回的std::slice_array 没有下标运算符。
  • 是的,你是对的。为了提高性能,最好使用您的解决方案。如果只是想为您的代码添加一些语法糖,我给出的示例会更好。
猜你喜欢
  • 1970-01-01
  • 2013-03-10
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多