Voivoid
Voivoid

Reputation: 755

How to find an element in mdspan

How to find an element in c++23 std::mdspan? Let's say there is some 2D mdspan. How can I find an element and get it's 2D indices?

I guess I can call data_handle() to get an access to underlaying data and do a 1D array search, but this will give me a 1D index. Does mdspan provide a method to map it back to 2D index?

Upvotes: 2

Views: 132

Answers (1)

Weijun Zhou
Weijun Zhou

Reputation: 4941

Use std::ranges::find with a custom projection.

#include <vector>
#include <algorithm>
#include <iostream>
#include <ranges>

int main(){
    std::vector vec = {1, 2, 3, 4, 5, 6, 7, 88, 9, 10, 11, 12};
    auto ms = std::mdspan(vec.data(), 2, 6);

    auto coeff_view = std::views::cartesian_product(std::views::iota(0uz, ms.extent(0)),
                                        std::views::iota(0uz, ms.extent(1)));
    auto iter = std::ranges::find(coeff_view, 88, [ms](const auto rc){
        auto [r,c] = rc;
        return ms[r, c];
    });

    auto [foundr, foundc] = *iter;

    std::cout << foundr << "," << foundc << '\n';
}

The above outputs 1,1.

Demo: https://godbolt.org/z/obW9jE3eW

Upvotes: 3

Related Questions