假设我有一个回溯算法,我需要从地图中删除一个元素,做一些事情,然后把它放回去。我不确定是否有一个好方法:
func(std::<K, V> map &dict) {
for (auto i : dict) {
remove i from dict;
func(dict);
put i back to dict;
}
}
我知道有一些方法可以在here中删除地图中的元素,但我不确定是否有办法实现上述内容。我知道我可以在for循环中创建一个新的dict并在func中传递它,但我想知道它是否可以使用相同的dict完成。
答案 0 :(得分:1)
你问的肯定是可能的。在尝试保持简单高效的同时,这是一种方法:
void func(std::map<K, V> &dict) {
for (auto i = dict.cbegin(); i != dict.cend(); ) {
auto old = *i;
i = dict.erase(i); // i now points to the next element (or dict.end())
some_other_func(dict);
dict.insert(i, old); // i is used a hint where to re-insert the old value
}
}
通过使用迭代器参数调用std::map::erase
并使用提示调用std::map::insert
,通过此循环进行的每次迭代的复杂性均为摊销常量。请注意,我假设您在第5行调用func
实际上应该是some_other_func
,因为递归调用func
会使您在第4行中仔细设置的迭代器无效。
但是,这不是进行此类处理的最有效方法(@rakurai应该考虑suggestion。
答案 1 :(得分:0)
此问题有answer here。
但是,您的问题可能是您希望在处理dict时忽略键K的功能。第二个参数怎么样&#34; K忽略&#34;并使该功能跳过该对?如果破坏了其他代码,则可以在声明中给它一个默认值,或者重载函数。