我目前正在使用一个向量来保存程序中的人。我正试图用
vectorname.erase(index);
我在函数中传递向量,以及要删除的元素。我的主要问题是如何在编译速度方面提高我的代码?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class person {
private:
string name;
public:
person() {}
person(string n):name(n){}
const string GetName() {return name;}
void SetName(string a) { name = a; }
};
void DeleteFromVector(vector<person>& listOfPeople,person target) {
for (vector<person>::iterator it = listOfPeople.begin();it != listOfPeople.end();++it) {//Error 2-4
if (it->GetName() == target.GetName()) {
listOfPeople.erase(it);
break;
}
}
}
int main(){
//first group of people
person player("Player"), assistant("Assistant"), janitor("Janitor"), old_professor("Old Professor");
//init of vector
vector<person> listOfPeople = { player, assistant, janitor, old_professor };
DeleteFromVector(listOfPeople, janitor);
}发布于 2017-03-27 01:51:06
不需要定义index,迭代器可以用于访问向量中的对象:
for (vector<person>::iterator it = listOfPeople.begin(); it != listOfPeople.end(); ++it) {//Error 2-4
if (it->GetName() == target.GetName()) {
listOfPeople.erase(it);
break;
}
}由于下一行是中断for循环,所以这里不考虑无效的迭代器问题。
发布于 2017-03-27 04:38:27
您不需要使用这个循环从向量中删除对象。只需使用如果
#include <algorithm>
//...
void DeleteFromVector(vector<person>& listOfPeople, const person& target)
{
// find the element
auto iter = std::find_if(listOfPeople.begin(), listOfPeople.end(),
[&](const person& p){return p.GetName() == target.GetName();});
// if found, erase it
if ( iter != listOfPeople.end())
listOfPeople.erase(iter);
}发布于 2020-05-27 14:04:00
listOfPeople.erase(
remove(listOfPeople(), listOfPeople.end(), target),
listOfPeople.end()
)“删除”操作在这个擦除-删除成语将所有的元素除目标移动到向量范围的前面,而“擦除”操作将删除所有的元素,在结束符合目标标准。这是非常有效的,尽管它没有迭代版本那么有表现力。
https://stackoverflow.com/questions/43036674
复制相似问题