c++如何将迭代器映射的集合作为键

c++ how can I iterator map of sets as key

本文关键字:集合 映射 迭代器 c++      更新时间:2023-10-16

我有这个地图:

std::map<std::set<int>, float> myMap;

myMap初始化为:

{ (7, 9), 0.63 } 
{ (7, 11), 0.66 } 
{ (7, 13), 0.72 }
{ (7, 16), 0.73 }
{ (7, 17), 0.67 } 
{ (9, 13), 0.63 } 
{ (9, 16), 0.65 }
{ (9, 18), 0.61 } 

我想比较这些集合,如,如果集合A(i1,i2,…in-1)等于集合B(j1,j2,…jn-1)使得i1=j1, i2=j2,.....1 = jn-1,那么:

创建集C(i1,i2,.....in,jn)

so 在第一次迭代后,我将有这些集合:

(7、9、11),(7、9、13),(7、9、16)、(17)7日,9日,(7、11、13),(7、11、16),(7、11、17),(7、13、16)、(17)7,13日,(7、16、17)

(9,13,16), (9,13,18), (9,16,18)

在第二次迭代后,我将有这些集合:

(7、9、11、13),(7 9 11、16)、(17)7日,9日,11日,(7、9、13、16),(7、9、13、17),(7、9、16、17)

(9,13,16,18) **停止,不再设置!* *

在第三次迭代之后,我将得到这些集合:(7、9、11、13、16)、(17)7,9,11,13日,(7、9、13、16、17),(7、9、13、16、17)* *停止,不再设置! !* *

这是代码

for (const auto& a : myMap)
    {   
        for (auto  b = ++myMap.begin(); b != myMap.end(); ++b)
        {
            bool equal = std::equal(a.first.begin(), --(a.first.end()), b->first.begin()); // tthanks to @povilasb
            if (equal)
            {
                std::set_union(a.first.begin(), a.first.end(), b->first.begin(), b->first.end(), std::inserter(dest1, dest1.begin()));
                for (set<int> ::iterator it = dest1.begin(); it != dest1.end(); it++)
                    cout << *it << " ";
                cout << endl;
                dest1.clear();
            }
            else // since `myMap` is already sorted, no need to continue comparing if 'equal` is false, so i exit the internal loop
                break;
        }
        }

我想编辑内部循环for (auto b = ++myMap.begin(); b != myMap.end(); ++b)所以b的状态总是从a之后的下一组开始

我试了for (auto b = ++a.first.begin(); b != myMap.end(); ++b)但我得到错误的b != myMap.end();

看来a应该保持它在嵌套循环中的位置:

for (auto a = myMap.begin(); a != myMap.end(); ++a)
{
    auto b = a;
    for (++b; b != myMap.end(); ++b)
    {
        // Replace "a." with "a->"
        ...
    }
}