Search code examples
c++structured-bindings

Structured bindings to get consecutive elements of a sub-vector without copying


I have a std::vector<T> vec where consecutive blocks of 3 elements are of interest. For ease of processing, I'd like to extract such elements. Currently, the code looks like:

const T& a = vec[i];
const T& b = vec[i + 1];
const T& c = vec[i + 2];

I'd like to use a structured binding to compress the extraction of a, b, c to a single line.

A simple option would be something along the lines of:

std::tuple<T, T, T> getElement(int i) {
    return std::make_tuple(vec[i], vec[i+1], vec[i+2]);
}

// ...
auto [a, b, c] = getElement(j);

The problem is that I would like to avoid useless copying of data. I'm not sure, but it seems that the vector elements will be copied here into the tuple. Would using std::tuple<T&, T&, T&> be an option?


Solution

  • Would using std::tuple<T&, T&, T&> be an option?

    It would, and there's already a utility for it in the standard library: std::tie. It accepts an arbitrary number of references (to different types even), and returns a tuple of references to the same objects. So your use case can be condensed to

    auto getElement(int i) {
        return std::tie(vec[i], vec[i+1], vec[i+2]);
    }