2010-08-14 95 views
3

代码:(?)C++迭代器做什么?

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++; 
    } 

我觉得lower_bound做一个二进制搜索,所以最后,不C++代码打算拿到重物想?它在哪里开始和停止?在这种情况下,循环是什么while?谢谢!

+4

'矢量 &res;'不会编译,因为引用都需要进行初始化。 – sbi 2010-08-14 21:51:36

+0

@sbi,看,为什么C++有这样一堆陌生人笔记?如此混乱 – ladyfafa 2010-08-14 21:54:42

+0

@ladyfafa:请参阅[这里](http://stackoverflow.com/questions/3479731/codingbat-like-site-for-c/3480268#3480268)最近有关C++复杂性的咆哮。真的,请相信[我昨天在评论中告诉过你](请参阅http://stackoverflow.com/questions/3480320/what-does-the-mean-in-c/3480333#3480333),并拿起初学者的C++书籍。 – sbi 2010-08-14 22:02:58

回答

6

lower_bound返回比所述第三参数少元素的最低迭代(即,在载体的位置) - 在这里,queryweight。然后while循环遍历剩余的元素,并且直到它到达具有大于或等于60的wight的元素将它们添加到矢量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++; 
} 
+0

@Stephen :)))明白了! – ladyfafa 2010-08-14 21:49:16

+0

@Stephen:已排序的向量是从最低到最高?或在相反的? – ladyfafa 2010-08-14 21:50:50

+0

查看sbi对该问题的评论。 – 2010-08-14 21:54:32