我正在尝试同时使用列表和 unordered_map 来存储同一组对象。我是 C++ 的新手,所以仍然熟悉迭代器。
假设我有以下测试代码:
class Test {
public:
int x;
int y;
int z;
Test (int, int, int);
}
Test t1 = Test(1,2,3);
Test t2 = Test(2,4,6);
Test t3 = Test(3,6,9);
std::list<Test> list;
std::unordered_map<int, Test> map;
list.push_back(t3);
list.push_back(t2);
list.push_back(t1);
map[101] = t1;
map[102] = t2;
map[103] = t3;
是否可以通过键查找对象,然后从对象的引用(或从 unordered_map 生成器?)生成列表迭代器?
所以如果我有 key 102,我可以在恒定时间内查找 t2。然后我想相对于列表中 t2 的位置向前/向后/插入/删除迭代。
我可以使用 find 获取指向 t2 的 unordered_map 迭代器。不知道如何生成从t2开始的列表迭代器(我只能在列表的开头或结尾生成迭代器,然后遍历。)
如果有人向我指出有关 STL 和迭代器的优秀教程,我将不胜感激。
谢谢!
事后思考: 这是一种可以接受的方法吗?我有很多对象,需要通过整数键有效地查找它们。我还需要保留它们的顺序(与这些整数键无关)并有效地插入/删除/遍历。
最佳答案
如果你想做的是这样的:
Is it possible to look up an object by key, and then generate a list iterator from the reference of the object (or from the unordered_map generator?)
然后你可以利用 list
迭代器在插入或删除时不会失效的事实(除非你删除那个特定的迭代器)并像这样重新组织你的结构:
std::list<Test> list;
std::unordered_map<int, std::list<Test>::iterator> map;
map.insert(std::make_pair(101,
list.insert(list.end(), t1)));
map.insert(std::make_pair(102,
list.insert(list.end(), t2)));
map.insert(std::make_pair(103,
list.insert(list.end(), t3)));
这样你的 map 查找就会给你你想要的东西:list
iterator
。
关于c++ - 对同一对象同时使用 Map 和 List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388487/