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个元素的类,例如{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;
}
}
相关文章:
- 如何删除作为C++联合的成员变量的字符串对象
- 系统C 从字符串对象sc_uint
- 为什么<string>字符串对象需要 #include 而不是字符串文本?
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- C 字符串对象错误字符
- 创建兼容的字符串对象
- 从对象数组打印字符串对象
- 将指针分配给字符串对象的第一个也是最后一个索引
- 比较字符串对象等于向量中的元素
- 传递给 std::runtime_error 的 ctor 的字符串对象的生命周期是多少?
- 如何移动 std::ostringstream 的底层字符串对象?
- 将 const 引用传递给临时字符串对象在 C++ 中安全吗?
- getline 没有为字符串对象分配任何值
- 在c++中删除字符串对象
- 如何在没有收到需要分号编译错误的情况下从 c++ 中的函数返回字符串对象
- 你能在C++中返回字符串对象的局部变量吗?
- 将字符串对象的地址传递给函数
- C++:从字符串对象中提取整数
- 是否有理由使用字符串 => 索引到向量的映射,而不是字符串 => 对象?
- 控制对多线程程序中字符串对象的访问的最佳方法