简体   繁体   中英

iterating c++ map keys

I'm trying to iterate a C++ std::map s' keys and push them onto an integer vector, so later I can get the minimum key/object.

Here is the relevant snippet:

//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

However I getting this error:

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 in the code snippet for LOOK BELOW comment for exact area of the problem.

How can I fix the syntax?

The keys in std::map are sorted according to the < operator. You can get the minimum key with

minMap.begin()->first

As for your error, std::min_element returns an iterator not an int. You need to deference the iterator first.

// 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM