2012-04-03 69 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