迭代C 地图键
iterating c++ map keys
我正在尝试迭代c std::map
s'键,然后将它们推到整数向量,因此以后我可以获取最小键/对象。
这是相关片段:
//shortest path algorithm
void Graph::shortest_path(std::vector<std::vector<int>> &_matrix) {
queue<int> unvisited;
queue<int> visited;
//initialize unvisited
for (int u=0; u<_matrix.size(); u++)
unvisited.push(u);
vector<Node> _neighbors;
Node neighbor;
Node * current=NULL;
Node * previous=NULL;
while (unvisited.size()>0) {
int r = unvisited.front();
if (current==NULL) {
current = new Node(r+1);
} else {
previous = current;
current = new Node(r+1);
current->setPrev(*previous);
}
cout << "current:" << current->getLabel();
cout << " _neighbors=" << endl;
_neighbors = neighbors(_matrix,r+1);
for (int n=0; n<_neighbors.size(); n++) {
cout << _neighbors[n].getLabel() << ",";
current->addToAdjacenyList(_neighbors[n]);
}
Node * backToRoot = NULL;
std::map<int,Node*> minMap;
for(int b = 0; b<current->getAdjacenyList().size(); b++) {
backToRoot = ¤t->getAdjacenyList()[b];
int distance = backToRoot->getWeight();
while (backToRoot!=NULL) {
backToRoot = backToRoot->getPrev();
distance = distance + backToRoot->getDistance();
}
backToRoot->setDistance(distance);
//add to map or priority queue were the key is distance & value is the node
minMap[distance] = backToRoot;
//get the keys from the map & get the minimum key/distance
vector<int> keys;
//LOOK BELOW
for(std::map<int,Node*>::iterator it = minMap.begin(); it != minMap.end(); ++it) {
keys.push_back(it->first);
cout << it->first << "n";
}
int min_key = std::min_element(keys.begin(),keys.end());
cout << "min_key:" << min_key ;
}
cout << endl;
unvisited.pop();
visited.push(r);
}//end while unvisited is NOT empty
}//end shortest path
但是我遇到了这个错误:
Graph.cpp:136:71: error: cannot convert '__gnu_cxx::__normal_iterator<int*, std::vector<int> >' to 'int' in initialization
int min_key = std::min_element(keys.begin(),keys.end());
在代码段中查看以下评论,以了解问题的确切区域。
如何修复语法?
std::map
中的密钥根据<
操作员进行排序。您可以使用
minMap.begin()->first
至于您的错误,std::min_element
返回迭代器而不是int。您需要先尊敬迭代器。
// Wrong
int min_key = std::min_element(keys.begin(),keys.end());
// Correct
auto it = std::min_element(keys.begin(),keys.end());
int min_key = *it;
相关文章:
- C++以迭代方式搜索混合类型地图
- 如何使用迭代器初始化地图的键字段?
- 通过迭代器打印出地图的值
- 迭代C 地图键
- C++同一地图上的嵌套迭代器?
- 为什么当我尝试在地图中迭代时我的值不显示
- C 通过指针的地图进行迭代
- 减去地图迭代器
- 如何在地图迭代器中检测最后一个元素
- 通过地图和打印内容迭代时,倒出输出
- 为什么我的地图迭代器中存在语法错误
- 迭代地图和擦除元素
- 通过C 地图周期性迭代,程序崩溃
- 默认构造的地图迭代器以增量进入无限环路 - 绿色山丘编译器
- C STL,我想知道地图中的双向迭代器和操作员[]之间有什么不同
- C 地图 - 自引用迭代器
- 使用迭代器将值插入嵌套地图
- 如何使用迭代器更新地图的第二个值
- 在地图迭代器上不支持非仿制地图上的平等运算符(==)
- 包装地图迭代器的地图