tags:

views:

128

answers:

1

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!

+6  A: 

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++;
}
Stephen
@Stephen:))) got it!!
ladyfafa
@Stephen: the sorted vector is from lowest to highest? or in the opposite?
ladyfafa
See sbi's comment on the question.
Tamás Szelei
Stephen
@Stephen, well i think it's better be "weight" property, spelling errors sorry
ladyfafa
sbi
@sbi Sorry, I wasn't meaning to accuse you of being that person. It's just that the reference was all I could see that I missed, so that's what I mentioned. I just get irritated when a (non-obviously bad/incorrect) answer gets a down-vote with no explanation!
Stephen
@Stephen: Okay, I green ticked you
ladyfafa
and thanks and I will keep this in mind in future
ladyfafa
@Stephen: I just noticed the downvote issues, take it easy~~~
ladyfafa