Vector 运行时错误-向量迭代器不可取消引用?

Vector 运行时错误-向量迭代器不可取消引用?,vector,iterator,Vector,Iterator,在课堂上,我制作了一个管理酒店的程序。当我的程序到达这个函数时,我得到一个运行时错误:向量迭代器不可解引用。我使用调试器查找问题区域,但我无法找出它的错误。有什么建议吗 Customer & ListOfCustomers::getByID(int id) { if(!sortedByID)sortByID(); vector<Customer>::iterator iter; Customer cus; cus.customerID=id; iter = lower_b

在课堂上,我制作了一个管理酒店的程序。当我的程序到达这个函数时,我得到一个运行时错误:向量迭代器不可解引用。我使用调试器查找问题区域,但我无法找出它的错误。有什么建议吗

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();
}
}
Customer&ListOfCustomers::getByID(int-id)
{
如果(!sortedByID)sortByID();
向量:迭代器iter;
客户关系;
cus.customerID=id;
iter=下限(customers.begin()、customers.end()、cus、compareCustomersByID);

如果((*iter).customerID==id)/您正在使用
下限
函数进行搜索。其目的与此稍有不同。下限的作用是:

返回一个迭代器,该迭代器指向排序范围[first,last]中不小于值的第一个元素

另一个定义来自:

具体地说,它返回可以插入值而不违反顺序的第一个位置

例如,如果您要查找的内容不在向量中,它将返回一个迭代器,该迭代器指向向量中最后一项的后面,并且该迭代器不存在,因此无法取消引用

看看这个例子:

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;
以下是输出:

30 found at position 2
80 not found

也许
iter==customers.end()
?@quasiverse我在尝试应用时仍然会遇到同样的错误,正如quasiverse所说,我的猜测是iter指针不正确。另外,发布下限函数也会很有用。@RStrad好的,我会处理指针。我添加了下限函数。它的内部包含算法。我很难获得整个事情都在块内,但我的错是…我没有意识到STL中有下限。我应该查一下。所以对我来说,这不太可能是问题。客户列表排序正确吗?另外,你确定了iter==customers.end()吗?
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