我有以下两个容器

map <classId, set< studentId> > allStudents;
map <classId, set< studentId> > assocStudents;

其中assocStudents是所有学生的子集。
获得allStudents减去assocStudents的差异以获得unassocStudents的差异的最有效方法是什么?
map <classId, set< studentId> > unassocStudents;

我能想到的最好的是
  • 遍历allStudents中的每个类,并在assocStudents中搜索该classId。
  • (如果该类存在于assocStudents中),则对studentId进行set_difference;
  • 否则复制整个StudentId集。

  • 有更聪明的方法吗?

    编辑:

    我对所提供的答案有些迷惑。

    假设我有以下数据
     allStudents contains classId 1, studentId {1, 11, 111, 1111}
                          classId 2, studentId (2, 22, 222, 2222}
     assocStudents contains classId 2, studentId {22, 2222}
    

    我喜欢最后一个容器
     unassocStudents contains classId 1, studentId {1, 11, 111, 1111}
                              classId 2, studentId (2, 222}
    

    set_difference不会给我以下内容
     unassocStudents contains classId 1, studentId {1, 11, 111, 1111}
    

    最佳答案

    这为您提供了所需的答案:

    #include <algorithm>
    #include <iostream>
    #include <iterator>
    #include <map>
    #include <set>
    
    using classId = int;
    using studentId = int;
    using map = std::map<classId, std::set<studentId>>;
    
    int main()
    {
        map allStudents{
            {1, {1, 11, 111, 1111}},
            {2, {2, 22, 222, 2222}},
        };
        map assocStudents{
            {2, {22, 2222}},
        };
        map unassocStudents;
    
        // Setup keys.
        for (auto const& i : allStudents) {
            auto& unassocSet = unassocStudents[i.first];
            auto& assocSet = assocStudents[i.first];
            std::set_difference(i.second.begin(), i.second.end(),
                                assocSet.begin(), assocSet.end(),
                                std::inserter(unassocSet, unassocSet.end()));
        }
    
        for (auto const& i : unassocStudents) {
            std::cout << "classId = " << i.first << '\n';
            for (auto const j : i.second) {
                std::cout << "\tstudentId = " << j << '\n';
            }
        }
    }
    

    See it working here

    08-04 12:25