从映射中取出Int值并将其迭代到二分图中

Taking Int values out of a map and iterating them into a bipartite graph C++

本文关键字:迭代 二分图 映射 Int      更新时间:2023-10-16

这对我来说相当复杂,希望对其他人来说不是这样。

我在一个映射中有一组256键/值项。我通过ifstream从文本文件中获取了地图上的数据。现在,我需要从映射中获取键/值对,我需要使用这些数据点来创建一个二部映射图

我需要做的是迭代每个键和值,并将它们放入bpGraph格式:

bool bpGraph[V][V] = { {0, 0, 0, 1, 0, ect.... 0}, //Key 1 Value 4
                        {0, 2, 0, 0, 0, ect.... 0}, // Key 2 Value 2
                        {0, 0},
                        {0, 0},
                        {0, 0},
                        {0, 0},
                        {0, 0}
                      };

基本上,我将查看映射并设置这个256x256数组中的所有256个值,并将正确的值设置为true,其中键为水平行,值为垂直行。

这是我当前的代码:

int main(){
    ifstream myfile("H:\School\CSC-718\paths.txt"); 
    std::map<int, int> mymap;
    pair<int,int> me;
    char commas;
    int a, b;
    vector<int> v;
    while (myfile >> a >> commas >> b){
        mymap[a] = b;
    }
    mymap;
    bool bpGraph[M][N] = {
        //...
    };
    cout << "Maximum number networks "
         << maxBPM(bpGraph);
    return 0;
}

问题:

能给我一些关于实施的建议吗?

可以使用迭代器迭代映射。从迭代器中,你可以分别使用'first'和'second'成员提取键和值。然后你可以把这些值放到你的数组中。

对于下面的代码,迭代映射并打印每个键和相关的值:

void MapExample(void)
{
    std::map<int, int> mymap;
    mymap[1] = 11;
    mymap[2] = 22;
    mymap[3] = 33;
    for (std::map<int,int>::iterator it=mymap.begin();it!=mymap.end(); ++it)
    {
        std::cout << it->first << "->" << it->second << "n";
    }
}

上面打印

1 - 11>

2 - 22>

3 - 33>

编辑:

我不确定我是否理解正确,但如果我这样做,你想建立一个等效的数据表示,使用256x256数组而不是映射。

迭代映射你会这样做:

    for (std::map<int,int>::iterator it=mymap.begin();it!=mymap.end(); ++it)
    {
         int key = it->first;
         int value = it->second;
         bpGraph[key-1][value-1] = 1;  //the indexes to the array are zero based, so you need to subtract 1, if your keys and values belong to {1, ... ,256}
    }

注意,需要将所有数组元素初始化为0。for循环执行后,只有当key (i+1)与value (j+1)相关联时,V[i][j]才=1。