C++ 结构错误 “No matching function for call ' 删除'

标签 c++

这个问题在这里已经有了答案:





Erasing elements from a vector

(5 个回答)


2年前关闭。




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

#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;
}

最佳答案

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,并在 vector 中找到它:

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

第二种方式:
新建operator==person_id类(class):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 并使用它来查找 vector 中的元素
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);
}

关于C++ 结构错误 “No matching function for call ' 删除',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59765160/

相关文章:

c++ - 混合数字类运算符重载 C++

C++ 类数组的神秘转移

c++ - 如何初始化堆以便它可以被常规 MFC dll 中的静态构造函数使用?

c++ - Qt 中信号槽的层次结构太深

c++ - 如何计算 Eigen 库中稀疏矩阵的逆

c++ - 缓存位图

c++ - 内部编译器错误 - 开关表达式中的模板化转换运算符

c++ - 数组指针算术 - 合法和未定义的行为

c++ - delete[] (ptr, 0) 的行为

c++ - Arduino EEPROM 获取损坏的值