换句话说,std::span
在 span 实例被销毁后,迭代器是否失效?
我有一个需要用不同布局迭代的向量。我试图std::span
避免编写大量迭代器样板文件或引入外部库依赖项。简化示例:
#include <iostream>
#include <span>
#include <vector>
template <size_t N>
struct my_view {
std::vector<int> vec;
auto as_span() {
return std::span<int[N]>((int(*)[N])vec.data(), vec.size() / N);
}
auto begin() {
return as_span().begin();
}
auto end() {
return as_span().end();
}
};
int main() {
std::vector vec {1, 2, 3, 4, 5, 6};
my_view<2> pairs {std::move(vec)};
for (auto pair : pairs) {
std::cout << pair[0] << " " << pair[1] << std::endl;
}
my_view<3> triplets {std::move(pairs.vec)};
for (auto triplet : triplets) {
std::cout << triplet[0] << " " << triplet[1] << " " << triplet[2] << std::endl;
}
return 0;
}