我可以希望从映射中擦除元素或通过迭代器设置元素不比对数差吗?
Can I hope that erasing elements from a map or set by iterator is no worse than logarithmic?
cppreference.com¹ 和 cplusplus.com² 都声称 set
或 map
容器上的 erase
如果将迭代器作为其参数,则为"amortized constant".
这几乎没有暗示其最糟糕的复杂性。我能希望它永远不会比对数差吗?至少有合理的实施?
¹http://en.cppreference.com/w/cpp/container/map/erase#Complexity
²http://www.cplusplus.com/reference/map/map/erase/#complexity
是的,你可以希望 std::map::erase(map::iterator)
的 worst-case 复杂度是容器大小的对数。
std::map::erase
有一个 two-argument 版本,它擦除一系列元素,给定迭代器定义范围的开始和限制。它的复杂性保证(在 Table 101 中,在 §23.2.4 [associative.reqmts] 中引用)为 O(log S + N),其中 S 是容器的大小,N 是容器的数量要擦除的元素。您可以在 O(log S) 中找到后继迭代器并使用 N=1 的 two-argument erase 成员函数,从而导致 O(log S) 时间。如果这不适用于 one-argument 版本,那将是非同寻常的。
这不是铁定的保证,但它是合理希望的基础。
cppreference.com¹ 和 cplusplus.com² 都声称 set
或 map
容器上的 erase
如果将迭代器作为其参数,则为"amortized constant".
这几乎没有暗示其最糟糕的复杂性。我能希望它永远不会比对数差吗?至少有合理的实施?
¹http://en.cppreference.com/w/cpp/container/map/erase#Complexity
²http://www.cplusplus.com/reference/map/map/erase/#complexity
是的,你可以希望 std::map::erase(map::iterator)
的 worst-case 复杂度是容器大小的对数。
std::map::erase
有一个 two-argument 版本,它擦除一系列元素,给定迭代器定义范围的开始和限制。它的复杂性保证(在 Table 101 中,在 §23.2.4 [associative.reqmts] 中引用)为 O(log S + N),其中 S 是容器的大小,N 是容器的数量要擦除的元素。您可以在 O(log S) 中找到后继迭代器并使用 N=1 的 two-argument erase 成员函数,从而导致 O(log S) 时间。如果这不适用于 one-argument 版本,那将是非同寻常的。
这不是铁定的保证,但它是合理希望的基础。