c++ - 重新索引值
问题描述
我是 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
非常感谢任何提示!
解决方案
以下是如何使用 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
推荐阅读
- angular - 行为主题的订阅增加一
- javascript - 通过Javascript自动单击具有唯一标签和类名的页面上的按钮的方法
- react-native - 可以从componentN之外的组件导航componentN(createAppContainer)吗?有可能吗?
- python - 使用 class_wight='balanced' 时如何找出 Logistic 回归中使用的原始权重值?
- css - 如果移动一个或另一个,如何使两个 div 靠近在一起
- reactjs - 如何在 react-testing-library 中的单选按钮上触发更改事件?
- angular - Angular 6 在本地主机上工作但不发布到服务器
- javascript - 如果表单字段有效并填写,则仅显示模式框 - JQuery
- swift - 重新排序时如何保持单元格颜色特性?
- android - WP REST API 和 React Native:如何显示不在 HTML 中的内容