c++ - vector 保存类对象,类对象每个对象包含 3 个字符串。如何找到特定字符串,然后删除整个元素?

标签 c++ c++11 vector erase erase-remove-idiom

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

我有一个 vector 来保存这组信息。我可以以什么方式查找集合中的单个元素(例如 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 行。 任何帮助将非常感激!!谢谢你!

最佳答案

尝试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

关于c++ - vector 保存类对象,类对象每个对象包含 3 个字符串。如何找到特定字符串,然后删除整个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33253368/

相关文章:

c++ - BGL 迭代宏、类型名和模板

c++ - Regex根据编译器替换不同的输出

c++ - 无法使用模板参数定义变量类型和大小的列表

c++ - 如何push_back到子 vector ?

c++ - 检查 vector 索引是否为空

c++ - 编译文件的 Netbeans 错误

c++ - 在可见性有限的 `std::terminate` 函数中调用 `noexcept` - gcc vs clang codegen

c++ - atomic_int_fastN_t 和 atomic_int_leastN_t 类型之间有什么区别

c++ - Intel 上的多线程比 AMD 慢得多

STL - STL count_if 的标准谓词