2015-10-21 39 views
2

我有一個包含3個元素的例如{first_name,Last_name,Phone}矢量包含類對象,類對象每個對象包含3個字符串。我如何找到特定的字符串,然後刪除整個元素?

我有一個保存這組信息的向量。我可以用什麼方式去查找集合中的單個元素,例如find(last_name),並刪除包含該特定姓氏的所有元素?

我已經嘗試了很多例子,並搜遍遍及全世界的谷歌。請幫忙。附加的代碼位:

int number = 4; 
vector <Friend> BlackBook(number); 

Friend a("John", "Nash", "4155555555"); 
Friend d("Homer", "Simpson", "2064375555"); 

BlackBook[0] = a; 
BlackBook[1] = d; 

現在,這只是設置相同的基本代碼。這是我嘗試過的一些事情。但是我越看越代碼所說的內容,看起來就好像它不允許一個字符串參數......但是我不知道如何給一個特定的字符串提供一個類的爭論......好吧我不知道我做錯了什麼。我有一種感覺,我可以用指針做到這一點,但整個指針的事情還沒有點擊。但是繼承了我嘗試過的一些事情。

vector <Friend> :: iterator frienddlt; 
frienddlt = find (BlackBook.begin(), BlackBook.end(), nofriend); 
if (frienddlt != BlackBook.end()) 
{ 
    BlackBook.erase(std::remove(BlackBook.begin(), BlackBook.end(), nofriend), BlackBook.end()); 
} 
else 
{ 
    cout << nofriend <<" was not found\n" << "Please Reenter Last Name:\t\t"; 
} 

當我編譯頭文件stl_algo.h打開,點到線1133 任何幫助將是非常讚賞的項目!謝謝!

+0

您可能需要將'C++'標記添加到您的問題中以吸引適當的受衆(並移除多餘的''類別')。 – WhiteViking

回答

2

嘗試remove_if

My example:

#include <iostream> 
#include <string> 
#include <algorithm> 
using namespace std; 

struct Friend { 
    string first_name; 
    string last_name; 
    string phone; 
}; 

bool RemoveByName (vector<Friend>& black_book, const string& name) { 
    vector<Friend>::iterator removed_it = remove_if( 
     black_book.begin(), black_book.end(), 
     [&name](const Friend& f){return f.first_name == name;}); 

    if (removed_it == black_book.end()) 
     return false; 

    black_book.erase(removed_it, black_book.end()); 
    return true; 
} 

int main() { 
    vector <Friend> black_book { 
     Friend {"John", "Nash", "4155555555"}, 
     Friend {"Homer", "Simpson", "2064375555"} 
    }; 
    if (RemoveByName(black_book, "John")) { 
     cout << "removed" << endl; 
    } else { 
     cout << "not found" << endl; 
    } 
    if (RemoveByName(black_book, "Tom")) { 
     cout << "removed" << endl; 
    } else { 
     cout << "not found" << endl; 
    } 
    for (int i = 0; i < black_book.size(); ++i) { 
     Friend& f = black_book.at(i); 
     cout << f.first_name << " " << f.last_name << " " << f.phone << endl; 
    } 
    return 0; 
} 

輸出:

removed 
not found 
Homer Simpson 2064375555 
+0

謝謝!!!有效。如果你有時間,你可以給你一些關於你的代碼的解釋,或許可以在這裏和那裏發表評論。無論如何非常感謝你的幫助。 –

+0

@MichaelLa,欲瞭解更多信息,請參閱[Erase-Remove Idiom](https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom)。 – Ralara

+0

此外,'if(removed_it == BlackBook.end())'檢查不是必需的。如果沒有條目匹配謂詞,那麼'remove_if'將返回一個與'BlackBook.end()'相同的過去末端迭代器;因此'BlackBook.erase(...'調用什麼都不會做,除非你想捕獲這個狀態並返回'true' /'false',如這個例子所示。 – Ralara

1

當然,你總是可以遍歷所有的朋友元素和手動刪除它們。

Blackbook::iterator friend = Blackbook.begin(); 
while (friend != Blackbook.end()) 
{ 
    if (friend->last_name == bad_name) 
    { 
     friend = Blackbook.erase(friend); 
    } 
    else 
    { 
     ++friend; 
    } 
} 
+1

如果可能,最好使用stl算法:它們使得它更容易理解什麼代碼呢。 –

相關問題