簡體   English   中英

迭代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 = &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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM