繁体   English   中英

C++ 删除向量中的对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM