C++ C++;-在std::map中查找相邻元素

C++ C++;-在std::map中查找相邻元素,c++,map,C++,Map,使用我在下面提到的示例,查找STL映射中相邻元素的最有效方法是什么: 假设我有一个整型字符串的映射: 1 -> Test1 5 -> Test2 10 -> Test3 20 -> Test4 50 -> Test5 如果我打电话: get_adjacent(1) // Returns iterator to 1 and 5 get_adjacent(2) // Returns iterator to 1 and 5 get_adjacent(24) // Ret

使用我在下面提到的示例,查找STL映射中相邻元素的最有效方法是什么:

假设我有一个整型字符串的映射:

1 -> Test1
5 -> Test2
10 -> Test3
20 -> Test4
50 -> Test5
如果我打电话:

get_adjacent(1) // Returns iterator to 1 and 5
get_adjacent(2) // Returns iterator to 1 and 5
get_adjacent(24) // Returns iterator to  20 and 50
get_adjacent(50) // Returns iterator to 20 and 50

使用
std::lower_bound
std::upper_bound
来实现这一点

更好的是,
std::map::equal_range
结合了这两种功能:

看现场直播


如果你想这样做,我认为
std::map
不一定是正确的选择。看看一些std算法:邻接对于地图来说毫无意义。从你的例子来看,你仍然不清楚“邻接”是什么意思。您能描述一下这意味着什么吗?如果您想要一个现成的答案,那么最好包含实际的代码,这样我们就不必编造上下文。这就是为什么我停止在我目前提供的细节级别/cc@XeoFirst,使用map成员,然后使用
equal_range
,它是
[下限(),上限()]
@Xeo这正是我刚刚发布的内容。我花了一些时间为迭代器获得有用的演示输出:)注意,
test(2)
应该是
1,5
而不是
5,5
test(24)
test(50)
应该是
20,50
@Xeo我只是在这里展示标准设施。我想OP可以从这里推断出来——其余的都是很普通的(稍微检查一下边界就可以了)。我选择到此为止,因为这很可能已经解决了问题,因为通常的解决方案的问题是
map::lower_bound
将返回第一个计算值不小于键的元素(请参阅),这意味着如果您请求
test(0.5)
,您将收到从1到5的间隔。
#include <map>
#include <iostream>

const auto data = std::map<int, std::string> {
    { 1  , "Test1" }, 
        { 5  , "Test2" }, 
        { 10 , "Test3" }, 
        { 20 , "Test4" }, 
        { 50 , "Test5" }, 
};

template <typename Map, typename It>
void debug_print(Map const& map, It it)
{
    if (it != map.end())
        std::cout << it->first;
    else
        std::cout << "[end]";
}

void test(int key)
{
    auto bounds = data.equal_range(key);

    std::cout << key << ": " ; debug_print(data, bounds.first)  ; 
    std::cout << ", "        ; debug_print(data, bounds.second) ; 
    std::cout << '\n'        ; 
}

int main(int argc, const char *argv[])
{
    test(1);
    test(2);
    test(24);
    test(50);
}
1: 1, 5
2: 5, 5
24: 50, 50
50: 50, [end]