[英]C++ Deleting an object in a vector
我目前正在使用一個向量來保存程序中的人員。 我正在嘗試刪除它
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);
}
不需要定義index
,迭代器可以用來訪問 vector 中的對象:
for (vector<person>::iterator it = listOfPeople.begin(); it != listOfPeople.end(); ++it) {//Error 2-4
if (it->GetName() == target.GetName()) {
listOfPeople.erase(it);
break;
}
}
由於下一行是中斷 for 循環,我們這里不考慮無效迭代器問題。
您不需要該循環來從向量中刪除對象。 只需使用std::find_if :
#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);
}
listOfPeople.erase(
remove(listOfPeople(), listOfPeople.end(), target),
listOfPeople.end()
)
這個erase-remove 慣用法中的“remove”操作將把除target 之外的所有元素移動到向量范圍的前面,“erase”操作將刪除滿足目標標准的所有元素。 即使它不像迭代版本那樣具有表現力,這也是非常有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.