vector包含类对象,每个类对象包含3个字符串.我如何找到特定的字符串,然后删除整个元素

A vector holds class objects, The class object contains 3 strings per object. How do i find the specific string, then delete the entire element?

本文关键字:字符串 对象 元素 然后 删除 包含类 包含 3个 vector 何找      更新时间:2023-10-16

我有一个包含3个元素的类,例如{first_name, Last_name, Phone}

我有一个包含这组信息的向量。以什么方式查找集合中的单个元素,例如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 foundn" << "Please Reenter Last Name:tt";
}

当我编译这个项目时,头文件stl_algorithm .h打开并指向第1133行。任何帮助都会非常感激!!谢谢你!

尝试remove_if

我的例子:

#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

当然,你总是可以遍历所有的Friend元素并手动删除它们。

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