8

Is there a functionality in the Standard Library which allows me to slice a std::slice or do I need to write something like

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

by myself?

0xbadf00d
  • 17,405
  • 15
  • 67
  • 107

1 Answers1

0

There is no such thing in standard library, as far as I can tell.

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

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

But if you are using a const std::valarray you can use the operator

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

that will return another std::valarray, and in that you can apply std::slice again.

// 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;
}
  • I'm using `std::slice` in a user-defined class. BTW the bad thing about `operator[](std::slice) const` in `std::valarray` is that it yields the sliced object by *copying* the corresponding elements. If the `std::valarray` is huge, that operation will lead to a serious performance penalty hidden behind an elegant notation. In my class I'm returning a proxy object which contains a reference to the actual one. That's what the non-const version of `operator[](std::slice)` in `std::valarray` does. But there, the returned `std::slice_array` has no subscript operator. – 0xbadf00d Apr 16 '16 at 10:29
  • Yes, you are right. For performance it is better to use your solution. The example that I give would be better if just want some syntactic sugar to your code. – Tiago Vieira Apr 16 '16 at 21:49