【发布时间】:2017-03-27 01:43:38
【问题描述】:
我目前正在使用向量来将人员保存在程序中。我正在尝试删除它
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);
}
【问题讨论】:
-
为什么你在
for中定义了迭代器,却不使用它? -
你做错了。您正在使用
erase但没有将其返回值作为新的迭代器,因此之后您将使用无效、损坏的迭代器。而且,还有一个更好的方法,你可以在这里看到 en.cppreference.com/w/cpp/algorithm/remove 和 en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom -
好的,我在使用
erase后立即看到了您的break,所以我猜您毕竟没有使用无效的迭代器。 -
不用那些东西,只需使用
find_if来查找管理员并使用它的返回值进行擦除。 Example. -
你为什么同时使用
it和index。迭代器的全部意义在于使用它而不是索引。选择其中之一,但不能同时选择两者。
标签: c++ vector visual-studio-2015 erase