Assuming the following snippet of code
set<int>::iterator it = st.begin();
it++;
What's the order of it++
. Does it take O(log n)?
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | nor | 152 |
Assuming the following snippet of code
set<int>::iterator it = st.begin();
it++;
What's the order of it++
. Does it take O(log n)?
Название |
---|
Yes.
It's O(1) amortized, as it just traverses binary tree going up and down, and O(log n) in a worst case for one ++ operation, as std::set uses red-black tree which has logarithmic height.
Very helpful. Thanks
Code from the post is
Beginning of the set is the leftmost element, and it's parent will be the next, so this code will always run in O(1). Am I right?
No, you're wrong.
First, the leftmost element isn't always a leaf, so the increment won't always work in O(1).
Second, I'm not sure that
set::begin()
must work in O(1) according to the C++ standard. So, I'd always rely only on the upper bound.Oh, I see now, thanks
It seems that if
begin()
is not a leaf then depth of its subtree is constant because black height of left subtree is 0, so black height of right subtree is 0 too. And it's either empty or one red vertex.Note, that I suppose that it's red-black tree and it's not guaranteed.
cppreference and cpkuspkus com say that std::set::begin() is constant but I'm not sure if it is reliable source
In C++11 23.2.1 "General container requirements", in Table 96 you have
In other words, iterating over the whole set takes
O(n)
worst case (inorder traversal). Executing a singleit++
(looking for successor) takesO(lg n)
worst case.