首页 > 解决方案 > 如何在 C++ STL 的集合中找到有序的后继或前驱

问题描述

C++ STL 中的集合是使用红黑/AVL 树或任何其他自平衡树实现的。那么,我怎样才能在其中找到有序的继任者或有序的前任?

标签: c++stlset

解决方案


set<int> s;

for (int i = 0; i < n; i++) {
    s.insert(i);
}

// returns an iterator pointing to x
auto p = s.insert(x);

// inorder successor can be found with incrementing iterator
// if it doesn't exists iterator to end to will be returned

if (++p.first != s.end()) {
    cout << *p.first  << endl;
}

推荐阅读