C++ Iterator做什么?

lad*_*afa 3 c++ iterator

码:

  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++;
  }
Run Code Online (Sandbox Code Playgroud)

我认为lower_bound做二进制搜索(?),所以最后,C++代码是否打算获得所需的权重?它开始和停止的地方?又是什么在while这种情况下循环呢?谢谢!

Ste*_*hen 6

lower_bound返回小于第三个参数的元素的最低迭代器(即向量中的位置)- 这里,queryweight.然后while循环遍历其余元素,直到它到达一个wight大于或等于60 的元素将它们添加到向量res.我假设输入向量w是排序的,否则这个函数没有多大意义.

逐行:

// 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++;
}
Run Code Online (Sandbox Code Playgroud)