我有一个Foo的列表,我也需要(恒定时间)随机访问,所以我只是创建了一个向量来将迭代器存储到列表项。注意,向量内容不需要与列表的顺序相同。尽管Foo需要知道它们在存储矢量中的位置,所以每个foo自然都会得到一个std::vector<std::list<Foo>::iterator>::iterator。这意味着存在递归,因为从原始的Foo中,您可以转到它在std::vector<std::list<Foo>:iterator>中的迭代器,从那里您可以再次取消引用这个条目,返回到原始的Foo。现在我不知道如何调试我的程序,因为调试和查看Foo类型的CLion (gdb)变量会产生递归错误( cf )。我的例子如下:
复制的步骤
example.cpp
#include <iostream>
#include <list>
#include <vector>
struct Foo {
size_t index{}; // just to demonstrate the order inside the list
std::vector<std::list<Foo>::iterator>::iterator storage_link{};
Foo(size_t index_) : index{index_} {}
};
int main() {
std::list<Foo> foos{};
std::vector<std::list<Foo>::iterator> storage{};
// populate the list with 2 entries
foos.push_back(Foo{0});
foos.push_back(Foo{1});
// populate storage, order in storage vector may be arbitrary
storage.push_back(std::prev(foos.end()));
storage.push_back(foos.begin());
// link list items to their storage iterator
foos.begin()->storage_link = std::next(storage.begin());
std::next(foos.begin())->storage_link = storage.begin();
// get first and second item from the list through the storage
auto second_foo{*storage.begin()};
auto first_foo{*((*std::next(storage.begin()))->storage_link)};
std::cout << "First storage item references Foo with index "
<< (*second_foo).index << "\n";
std::cout << "Second storage item references Foo with index "
<< (*first_foo).index << "\n";
return 0;
}用
g++ -g -O0 -std=c++17 example.cpp -o example然后使用gdb进行调试,并尝试打印变量second_foo。
gdb ./example
(gdb) break /full/path/to/example.cpp:37
(gdb) run
Breakpoint 1 at 0x1459: file main.cpp, line 37.
(gdb) run
Starting program: /full/path/to/example
First storage item references Foo with index 1
Second storage item references Foo with index 0
Breakpoint 1, main () at example.cpp:37
37 return 0;
(gdb) p second_foo
$1 = Python Exception <class 'RecursionError'> maximum recursion depth exceeded while getting the str of an object:
{index = 1, storage_link = {index = 1, storage_link = {index = 1, storage_link = {index = 1, storage_link = {index......最后一行的递归还在继续,我不知道如何让gdb忽略这一点。
发布于 2021-08-03 03:23:55
我有一个Foo列表,我也需要(恒定时间)随机访问,所以我只是创建了一个向量来将迭代器存储到列表项。
将迭代器存储在容器中几乎从来都不是正确的做法,而且很可能会导致微妙的错误。
如果您需要对Foo进行固定时间的随机访问,请将指向它们的指针存储在向量中.
https://stackoverflow.com/questions/68610860
复制相似问题