【发布时间】:2016-06-19 04:20:28
【问题描述】:
我有一个包含 unordered_map 的迭代器的向量,我想在迭代器上使用 std::rotate,但我一定遗漏了一些东西。
当我做类似的事情时代码可以工作
std::vector<std::unordered_map<int, int>::iterator> _lruList;
void used(std::unordered_map<int, int>::iterator& it, int type) {
if (type == 0) {
auto item = _lruList.begin();
while (item != _lruList.end()){
if (*item == it){
std::rotate(item, item + 1, _lruList.end());
return;
}
item++;
}
}
}
但我希望代码像这样工作,因为这个函数被调用了很多次,其中额外的 while 循环增加了额外的不必要的时间复杂度
std::vector<std::unordered_map<int, int>::iterator> _lruList;
void used(std::unordered_map<int, int>::iterator& it, int type) {
if (type == 0) {
std::rotate(it, it + 1, _lruList.end()); //error on it
return;
}
}
编辑:更多代码,我看到它的类型和 _lruList.end() 冲突。无论如何,我可以解决这个问题以在不遍历向量的情况下仍然完成我想做的事情吗?
经过进一步调试,根据 VS2015,it + 1 似乎给了我一个"error type"。
std::unordered_map<int, int>::iterator found = _cache.find(key);
// if key doesn't exist, return -1
if (found == _cache.end()) {
return -1;
}
// if key exists, return value and update lru
used(found, 0);
return found->second;
如果这有助于回答我的问题,我可以提供更多代码 sn-ps。
任何帮助将不胜感激!
【问题讨论】:
-
“其中额外的 while 循环增加了额外不必要的时间复杂度” -- 你为什么认为它是不必要的?
-
@Benjamin Lindley 好吧,因为我认为这是我的代码超时的部分。这是 LeetCode 上的一个叫做 LRU Cache 的问题,其中有一个时间限制,我的代码时间超过了。所以我只是想找出在不首先改变我的数据结构的情况下降低时间复杂度的方法。我想“不必要”是一种不好的表达方式
标签: c++ vector rotation iterator unordered-map