2010-08-14 96 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