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 | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
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.