首页 > 解决方案 > 重新索引值

问题描述

我是 C++ 编程的新手,并且有一个任务,其中包含一组值的文件并用于创建邻接图。.txt 文件是这样的

1 3 22.5
3 1 22.5
8 5 14.2
3 5 2.5

讲师要求我们使用无序映射,但我不知道如何使用它来重新索引前两个 int 值(浮点值是节点之间的距离)。我可以迭代并用这些值填充地图吗?如果是这样,怎么做?

预期结果是:

0 - 1
1 - 3
2 - 5
3 - 8

非常感谢任何提示!

标签: c++unordered-mapadjacency-matrix

解决方案


以下是如何使用 anunordered_map重新索引顶点值。

注意:我没有得到与您所需相同的输出,因为我没有处理顶点的递增顺序,因为在重新索引时它并不重要。但是,如果您特别需要,可以对其进行修改。

此外,输出未排序,因为unordered_map未按排序顺序存储键。如果您想要排序的键,请使用 amap代替。

void reindexing(){
    freopen("input.txt", "r", stdin);

    unordered_map<int, int> mp;
    int to, from, i=0;
    double cost;

    // declaring a vector to store the reindexed edges
    vector<pair<pair<int, int>, double> > edges;

    while(cin>>from){
        // This loop runs till you are able to get vertices from input file
        cin>>to>>cost;

        // Now check if the vertices are already present in the unordered_map
        if(mp.find(to)==mp.end()){
            // If the control reaches here, then the vertex to is not found in map
            mp[to] = i++;
        }

        // similarly check for the from vertex
        if(mp.find(from)==mp.end()){
            // If the control reaches here, then the vertex to is not found in map
            mp[from] = i++;
        }
        edges.push_back({{mp[from], mp[to]}, cost});
    }
    
    // Printing the re-indexed vertex values
    for(auto it=mp.begin();it!=mp.end();it++){
        cout<<it->second<<" - "<<it->first<<endl;
    }

    //... further processing of edges vector to build adjacency matrix
}
Output:
2 - 5
0 - 3
3 - 8
1 - 1

推荐阅读