最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在 std::set 中查找邻居

SEO心得admin57浏览0评论
本文介绍了在 std::set 中查找邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 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.

发布评论

评论列表(0)

  1. 暂无评论