迭代c ++映射键

时间:2018-04-03 23:44:03

标签: c++ stl

我正在尝试迭代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());

在代码片段中查找问题的确切区域的LOOK BELOW评论。

如何修复语法?

1 个答案:

答案 0 :(得分:2)

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;
相关问题