C++ 删除和更新向量中的特定元素<;结构>;
我想请你帮我完成以下我必须解决的任务 有一个结构和一个向量:C++ 删除和更新向量中的特定元素<;结构>;,c++,search,vector,C++,Search,Vector,我想请你帮我完成以下我必须解决的任务 有一个结构和一个向量: struct SPerson { string name; string address; string birthcertificatenumber; }; std::vector<SPerson> People; 删除功能: bool UpdatePerson(const string & name, const string & address, const string & n
struct SPerson {
string name;
string address;
string birthcertificatenumber;
};
std::vector<SPerson> People;
删除功能:
bool UpdatePerson(const string & name, const string & address, const string & newaddress)
{
auto it = find_if(begin(People), end(People), [=] (SPerson const& f) {
return (strcasecmp(name.c_str(), f.name.c_str()) == 0) and (strcasecmp(address.c_str(), f.address.c_str()) == 0);
});
bool found = (it != end(People));
if (found == true)
{
it->address = newaddress;
return true;
}
return false;
}
bool DeletePerson(const string & name, const string & address)
{
auto it = find_if(begin(People), end(People), [=] (SPerson const& f) {
return ((strcasecmp(name.c_str(), f.name.c_str()) == 0) and (strcasecmp(address.c_str(), f.address.c_str()) == 0));
});
bool found = (it != end(People));
if (found == true)
{
People.erase(it);
items--;
return true;
}
return false;
}
由于您已经完成了足够的插入、删除和搜索操作,我建议您使用Hashmap/Unorderedmap而不仅仅是vector。我们将能够在O(1)时间复杂度内完成这些操作 查看以下示例:
这看起来对你合适吗
#include <algorithm>
auto it = find(People.begin(), People.end(), <value>);
if (it != People.end())
//do something with it, erase using it.erase()
#包括
auto it=find(People.begin(),People.end(),);
if(it!=People.end())
//用它做点什么,用它擦除。擦除()
对其他函数也执行同样的操作,只需在包含return关键字的行的比较中,将函数参数替换为SPerson的正确字段是否考虑为此使用数据库。大多数主流数据库都支持您的所有需求,包括多个索引、大量数据和区分大小写。请注意,如果您不想依赖外部数据库,也可以在应用程序中嵌入数据库实现。在示例数据中,向量按街道排序,是真的吗?使用
std::sort
保持向量排序,并使用std::lower_bound
查找要更改/删除的元素。这应该会给出O(logn)
Hash映射是这里使用的最基本的东西。如果禁止使用std::map,那么您可能需要编写自己的。谢谢您的评论。不幸的是我不能使用数据库,否则我会的。我应该有O(logn)是的。我听说了下限,但问题是我不知道如何将它应用于这个案例,否则我不会在这里写请求帮助:)否则很好,但不能满足“我需要快速地做动作-非线性”。并且要求类具有平等性,这一点没有被证明是事实。嗨,谢谢你的回答。我更新了我的文本,所以你可以注意到这个函数对于成千上万条记录来说速度很慢。它是线性的。你可以做的是寻找一个搜索算法来实现,而不是FIFIIF函数:例如,二进制搜索算法。当然,我知道:(但是,我不知道如何实现它,否则我不在这里写:)寻找C++实现。
DeletePerson( string& name, string& address)
{
auto iter = std::find_if(People.begin(), People.end(), [&](const SPerson& elem) {
return (elem.name == name && elem.address == address)
});
if (iter != People.end() )
{
People.erase(iter); // here you erase it or you can update it if you want
}
}