2015-04-24 78 views
0

我不明白这个函数的问题是什么,我在过去做过类似于这个的东西,它工作正常,但现在当我尝试运行此函数时,我得到错误无法取消引用矢量迭代器

"Unable to dereference vector iterator" 

这是继这是有道理的,因为这是它被dereferenced其中线curr->setName(new_name);。也只是为了清楚所有在这个方法中使用的函数和类自行工作,我只是没有为了空间而插入它们。

void System::modify(PC a){ 
    char x; 
    curr = find(begin(comps), end(comps), a); 

    cout << "What would you like to modify:" << endl; 
    cout << "a - Name" << endl; 
    cout << "b - IP" << endl; 
    cout << "c - Password" << endl; 

    cin >> x; 
    if(x == 'a'){ 
     string new_name; 
     cout << "What would you like to rename the computer to: "; 
     cin >> new_name; 
     curr->setName(new_name); 
    } 

    if(x == 'b'){ 
     string new_IP; 
     cout << "What would you like the new IP address to be: "; 
     cin >> new_IP; 
     curr->setIP(new_IP); 
    } 

    if(x == 'c'){ 
     curr->setNewPass(); 
    } 

    else{ 
     cout << "Choice is not valid" << endl; 
     return; 
    } 
} 
+4

您是否检查确认'curr!= end(comps)'并且comps不是空的? – NathanOliver

+0

@NathanOliver显然不是。 –

+0

你应该检查'curr!= end(comps)'并决定如何处理一个不存在的PC –

回答

0

看来,价值a在此声明

curr = find(begin(comps), end(comps), a); 

curr等于end(comps)没有被发现。

您应该检查搜索是否成功。

例如

if ((curr = find(begin(comps), end(comps), a)) != end(comps)) 
{ 
    // the search was successfull 
} 
0

目前还不清楚如何在PC所不能比拟的。但似乎查找函数返回结束(comps),这意味着在列表/向量/无论什么都没有“PC a”。你应该检查PC上已经发现

if(curr!=end(comps)) { 
// do whatever you wont with corr 
} 
else { 
//nothing has been found 
} 
2

您需要修改你的功能 - 它应该检查,find()是否找到一点事都没有:

void System::modify(PC a){ 
    char x; 
    curr = find(begin(comps), end(comps), a); 

    if(curr == end(comps)) 
    { 
     cout << "Specified PC was not found!" << endl; 
     return; 
    } 

    //... 
} 

文档页find()说:

返回值

范围中第一个元素的迭代器,它与val进行比较。 如果没有元素匹配,则函数返回last

last在这种情况下是end(comps)