ladyfafa
ladyfafa

Reputation: 7269

C++ Iterator do what?

Code:

  vector<weight *> &res;
  vector<weight>::iterator it = lower_bound(w.begin(), w.end(), queryweight);
  while(it != w.end()) {
      weight *w  = &(*it);
      if(w->weight >= 60) break;
      res.push_back(w);
      it++;
  }

I think the lower_bound do a binary search (?), so in the end, does the C++ code intend to get the weights wanted? Where it starts and stops? And what does the while loop in this case do? thanks!

Upvotes: 3

Views: 275

Answers (1)

Stephen
Stephen

Reputation: 6087

lower_bound returns the lowest iterator (i.e. position in the vector) of an element that is not less than the third parameter - here, queryweight. The while loop then goes through the remaining elements and, until it reaches an element that has a wight of greater than or equal to 60 adds them to the vector res. I assume the input vector w is sorted, otherwise this function wouldn't make much sense.

Line by line:

// Declare a vector of pointers to 'weight' objects, called res.
// (I assume here that the "&" in the original question was a mistake.)
vector<weight *> res;

// Find the iterator that points to the lowest element in vector 'w'
// such that the element is >= queryweight.
vector<weight>::iterator it = lower_bound(w.begin(), w.end(), queryweight);

// From this element forwards until the end of vector 'w'
while(it != w.end()) {
    // Get a pointer to the element.
    weight *w  = &(*it);
    // If the 'wight' property of this element is >= 60, stop.
    if(w->wight >= 60) break;
    // Push the element onto the 'res' vector.
    res.push_back(w);
    // Move to the next element.
    it++;
}

Upvotes: 6

Related Questions