2012-04-03 73 views
1

對於上課,我正在制定一個管理酒店的計劃。當我的程序到達這個函數時,我得到一個運行時錯誤:向量迭代器不可取的。我使用調試器來查找問題區域,但我無法弄清楚它有什麼問題。有什麼建議麼?運行時錯誤 - 向量迭代器不可忽略?

Customer & ListOfCustomers::getByID(int id) 
{ 
if(!sortedByID)sortByID(); 
vector<Customer>::iterator iter; 

Customer cus; 
cus.customerID=id; 

iter = lower_bound(customers.begin(),customers.end(),cus,compareCustomersByID); 

if( (*iter).customerID == id) // <---DEBUGGER SAYS ERROR HERE IN THIS LINE 
{ 
    return *iter; 
} 
else 
{ 
    return NullCustomer(); 
} 
} 

這裏是lower_bound函數。它是#include內部算法

template<class _FwdIt, 
    class _Ty, 
class _Pr> inline 
_FwdIt lower_bound(_FwdIt _First, _FwdIt _Last, 
    const _Ty& _Val, _Pr _Pred) 
{// find first element not before _Val, using _Pred 
// _DEBUG_ORDER_PRED(_First, _Last, _Pred); 
return (_Rechecked(_First, 
    _Lower_bound(_Unchecked(_First), _Unchecked(_Last), _Val, _Pred, 
      _Dist_type(_First)))); 
} 

編輯:添加一個空格,以便lower_bound函數將被正確格式化爲代碼。

+1

也許'ITER == customers.end()'? – quasiverse 2012-04-03 00:47:37

+0

@quasiverse我仍然遇到同樣的錯誤,當我嘗試應用 – Mike 2012-04-03 00:57:44

+0

像quasicverse說,我的猜測是iter指針是不正確的。另外,發佈lower_bound函數會很有用。 – RStrad 2012-04-03 01:11:22

回答

0

您正在使用lower_bound函數進行搜索。它的目的有點不同。 This是什麼呢LOWER_BOUND:

返回指向第一個元素在不超過比較少值排序的範圍[first,last)中的迭代器。

而且從here另一個定義:

具體地,它返回其中可以在不違反排序被插入值的第一位置。

因此,舉例來說,如果你正在尋找的東西不在矢量,它會返回在矢量點的最後一個項目一個迭代器,而迭代器不能因爲它取消引用不存在。

看看這個例子:

int myints[] = {10,20,30,30,20,10,10,20}; 
vector<int> v(myints,myints+8);   // 10 20 30 30 20 10 10 20 
vector<int>::iterator low; 

sort (v.begin(), v.end());    // 10 10 10 20 20 20 30 30 

low=lower_bound (v.begin(), v.end(), 60); //       ^it will point here 

cout << "lower_bound at position " << int(low- v.begin()) << endl; 

正如你可以從輸出中看到的,迭代器將指向向量(指數8)第9元。但矢量只有8個元素(索引0-7)。對此的解釋是,您可以在索引8處將新項目插入向量中,而不會違反順序。

我認爲你真正想要的是find函數。下面是一個例子:

int myints[] = {10,20,30,30,20,10,10,20}; 
vector<int> v(myints,myints+8);   // 10 20 30 30 20 10 10 20 

vector<int>::iterator find_it1 = find(v.begin(), v.end(), 30); 
vector<int>::iterator find_it2 = find(v.begin(), v.end(), 80); 
if(find_it1 == v.end()) 
cout << "30 not found" << endl; 
else 
cout << "30 found at position " << int(find_it1 - v.begin()) << endl; 

if(find_it2 == v.end()) 
cout << "80 not found" << endl; 
else 
cout << "80 found at position " << int(find_it2 - v.begin()) << endl; 

這裏是輸出:

30 found at position 2 
80 not found