迭代C 地图键

iterating c++ map keys

本文关键字:地图 迭代      更新时间:2023-10-16

我正在尝试迭代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 = &current->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;