Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Iterator do what?

Tags:

c++

iterator

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!

like image 483
ladyfafa Avatar asked Mar 01 '26 15:03

ladyfafa


1 Answers

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++;
}
like image 160
Stephen Avatar answered Mar 04 '26 04:03

Stephen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!