【发布时间】:2020-06-05 08:39:15
【问题描述】:
#include <vector>
#include <array>
int main() {
typedef std::array<int,2> point;
typedef std::vector<std::reference_wrapper<point>> route;
std::vector<std::vector<point>> lattice = {
{point{ {0,0} },point{ {0,1} }},
{point{ {1,0} },point{ {1,1} }}
};
route r = {&lattice[0][0],&lattice[0][1]};
point last = r.back().get();
}
最后一行不会编译,因为“不允许不完整的类型”。当我在互联网上搜索时,一篇论文似乎解决了这个问题:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0357r3.html。那篇论文刚好在我的水平之上。所以我不确定。有人会对此问题进行确认或解决方案吗?
另外,解决方法表示赞赏:
我正在尝试将路线存储在不太大的格上。会有很多路线(格子密集)。所以,我在想,在一条路线中,存储点的引用而不是点以节省内存。
【问题讨论】:
-
您是否知道您正在使用“范围”构造函数初始化
r?也就是说,例如,route r = {&lattice[0][0],&lattice[1][1]};不起作用。产生未定义行为的现场演示:godbolt.org/z/dvXCEG. -
@DanielLangr 也许
c++ route r = {std::ref(lattice[0][0]),std::ref(lattice[0][1])};更好。 -
我认为
route r = {lattice[0][0],lattice[0][1]};应该足够了。
标签: c++ vector reference-wrapper