2015-04-24 31 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)