首页 > 解决方案 > C++ 结构错误“调用‘擦除’没有匹配函数

问题描述

矢量擦除功能会引发错误,而清除功能有效。这是什么原因..?

#include <algorithm>
#include <vector>
#include <iostream>
struct person_id{
    person_id() = default;
    person_id(int id) : p_id (id) {}

    bool operator==(const person_id& other) { return p_id == other.p_id; }
    int p_id;
};
using std::cout;
using std::endl;

int main(int argc, char* argv[]) {
    std::vector<person_id> people;

    person_id tmp_person;
    tmp_person.p_id = 5;
    people.push_back(tmp_person);

    people.erase(5); // error : “No matching function for call 'erase'
    people.clear(); // works

    return 0;
}

标签: c++

解决方案


std::vector::erase()iterator. 所以如果你想删除第 6 个元素,你需要这样做: people.erase(people.begin() + 5);. 如果要删除第一个元素,只需使用people.erase(people.begin());

参考: http ://www.cplusplus.com/reference/vector/vector/erase/

编辑:擦除符合条件的元素:

第一种方法:person_id使用需要的 id 创建 temp,并在向量中找到它:

person_id personToCheck(5);
auto iter = std::find(people.begin(), people.end(), personToCheck);
if(iter != people.end())
{
   people.erase(iter);
}

operator==第二种方式:在person_id类 中新建:bool operator==(const int ID) { return p_id == ID; }

auto iter = std::find(people.begin(), people.end(), 5); //the 5 is the ID
if(iter != people.end())
{
   people.erase(iter);
}

第三种方式:创建 lambda 并使用它来查找向量中的元素

auto iter = std::find_if(people.begin(), people.end(), [](const person_id &p) { return p.p_id == 5; });
if(iter != people.end())
{
   people.erase(iter);
}

推荐阅读