189 8069 5689

c++:输出高维vector的shape并支持结构化绑定-创新互联

来自学弟的问题:一个vector>>v, 写一个模板函数Size(), 然后可以直接auto [n,m,k] = Size(v)获取这个高维矩阵的各维维度?

创新互联主营亳州网站建设的网络公司,主营网站建设方案,app软件定制开发,亳州h5成都微信小程序搭建,亳州网站营销推广欢迎亳州等地区企业咨询
#include#include#include#include 

using std::vector;

templatestruct Dimension {static constexpr std::size_t value = 0; };
templatestruct Dimension>{static constexpr std::size_t value = 1 + Dimension::value; };
templateinline constexpr size_t dim = Dimension::value;

template>std::arrayshape(const T & a)
{std::arrayresult{a.size()};
    if constexpr (N>1) {auto sub = shape(a[0]);
        std::copy(sub.begin(), sub.end(), result.begin()+1);
    }
    return result;
}


#define assert_eq(a, b) assert((a) == (b))

int main() {static_assert(dim== 0);
    static_assert(dim>== 1);
    static_assert(dim>>== 2);
    static_assert(dim>>>== 3);

    {//        assert_eq(shape(1), (std::array{})); // compile error
    }
    {vectorb = {1, 2, 3};
        assert_eq(shape(b), (std::array{3}));
    }
    {vector>c = {{"a", "b", "c"}, {"c", "d", "e"}};
        assert_eq(shape(c), (std::array{2, 3}));
    }
    {vector>>d = {{{"a", "b", "c"}, {"c", "d", "e"}},
            {{"a", "b", "c"}, {"c", "d", "e"}},
        };
        assert_eq(shape(d), (std::array{2, 2, 3}));

        auto [a, b, c] = shape(d);
        assert_eq(a, 2);
        assert_eq(b, 2);
        assert_eq(c, 3);
    }
}

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


文章题目:c++:输出高维vector的shape并支持结构化绑定-创新互联
本文URL:http://jkwzsj.com/article/hdics.html

其他资讯