c++ - 是否有一种优雅的方式来遍历 2 个 map 并比较值( map 具有相同类型)

标签 c++ stl stdmap

假设我有 2 张 map :

map<int,vector<int>> id2courses;
map<int,vector <int>> id2allowed_courses;

而且我想针对每个键 (id) 查看类(class)列表是否仅包含该 ID 允许的那些类(class)。它可以很容易地用 for 循环完成,但我想利用 std::map 是有序的这一事实,也就是我想在两个映射中前进(用较小的键递增迭代器),然后当我按下相等的键时我想做比较。 我知道我可以用非平凡的 while 循环来做到这一点,但我想知道是否有内置的 STL 方法来做到这一点

最佳答案

使用 std::set_intersection 有点骇人听闻:

map<int,vector<int>> id2courses;
map<int,vector <int>> i2allowed_courses;

set_intersection(id2courses.begin(), id2courses.end(),
                 i2allowed_courses.begin(), i2allowed_courses.end(),
                 null_output_iterator(),
                 compare_and_do_something_if_same_key);

null_output_iterator来自问题 Discarding the output of a function that needs an output iterator .

compare_and_do_something_if_same_key将通过 pair<const int, vector<int>>从每张 map 。如果 key 相等,您可以进行所需的处理。您还需要返回一个 bool 值来表示元素的顺序:

bool compare_and_do_something_if_same_key(
    pair<const int, vector<int>& a, pair<const int, vector<int>& b)
{
    if(a.first == b.first) {
        doProcessing(a, b);
    }
    return a.first < b.first;
}

Caveat Emptor:文档说比较函数不能修改被比较的对象。我认为这意味着不得以会导致订购问题的方式进行修改。因为您没有按 second 订购pair 中的值我认为这不太重要。

编辑以提高可读性:

这可以包装成一个命名函数:

template<typename Map, typename KeyValueProcessor> 
void process_values_for_matching_keys(
    Map& map1, Map& map2, KeyValueProcessor& keyValueProcessor);

并用作:

process_pairs_for_matching_keys(id2courses, i2allowed_courses, doProcessing);

关于c++ - 是否有一种优雅的方式来遍历 2 个 map 并比较值( map 具有相同类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14871232/

相关文章:

c++ - 尝试编写自定义 allocate_shared 分配器并使其成为 thread_local 时崩溃

C++11 在 Lambda 中捕获成员变量

C++ - 已排序 std::vector 中元素的索引

c++ - 自定义迭代器运算符重载

c++ - 字符转QString

c++ - opencv分割返回黑色图像

c# - 为什么 STL 中的 set_intersection 这么慢?

c++ - 如何在迭代器位置后插入元素

c++ - 如何通过指针访问 vector ?

C++ std::map - 如果一个线程写入而另一个线程始终使用不同的键读取,则线程安全吗?