我正在尝试在 std::set 中查找元素的下一个/上一个邻居.
I am trying to find the next / previous neighbor of an element in std::set.
我尝试做类似的事情:
std::set<int> s; for (int i = 0; i < 10; ++i) { s.insert(i); } std::set<int>::iterator iter = s.find(5); EXPECT_EQ(5, *(iter++));但它不起作用.
在高层次上,似乎从红黑树中可以在 O(logN) 中找到下一个/上一个元素,所以问题是 std::set 是否支持它?
At a high level, it seems like from a red-black tree it is possible to find the next / previous element in O(logN), so the question is does std::set support it?
推荐答案如果你需要使用 preincrement ie ++iter 而不是 postincrement ie iter++ 来递减迭代器想在这样的一行中做到这一点:
You need to decrement the iterator using preincrement i.e. ++iter rather than postincrement i.e. iter++ if you want to do it in a single line like that:
#include <iostream> #include <set> int main() { std::set<int> s; for (int i = 0; i < 10; ++i) { s.insert(i); } std::set<int>::iterator iter; iter = s.find(5); std::cout << "The number after 5 is: " << *(++iter) << "\n"; iter--; // Go back to 5 (Here it doesn't matter if you use postdecrement or predecrement) std::cout << "The number before 5 is: " << *(--iter) << "\n"; return 0; }输出:
The number after 5 is: 6 The number before 5 is: 4请注意,在获取下一个/上一个元素之前,您应该检查您的迭代器是否不在末尾或开头.
Note you should check that your iterator is not at the end or beginning as well probably before getting the next/previous element.