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

标签 c++ dictionary

使用我在下面提到的示例在 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_boundstd::upper_bound

更好的是 std::map::equal_range 结合了两者的力量:

观看直播 http://liveworkspace.org/code/d3a5eb4ec726ae3b5236b497d81dcf27

#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]

关于C++ - 在 std::map 中查找相邻元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12753926/

相关文章:

c++ - 为什么我的派生类找不到我的基类的类型别名?

c++ - 重新声明类名 class-key

c++ - 如何在 C++ 中的不同 map 之间共享 key ?

python - 如何按值对字典进行排序并返回格式化字符串列表?

python - 循环遍历 .csv 文件,条件位于不同列中

c++ - 更改线程实时调度策略失败: CONFIG_RT_GROUP_SCHED=y

c++ - ROOT 中带有变量的命令

c++ - 为什么这个静态成员即使存在也没有构造?

python - 从字符串创建字典

python - 如何拆分字符串并将其子字符串与子字符串列表匹配? - Python