【问题标题】:C++ Struct Error “No matching function for call 'erase' [duplicate]C ++结构错误“没有用于调用'erase'的匹配函数[重复]
【发布时间】:2020-05-03 00:45:24
【问题描述】:

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

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

【问题讨论】:

  • 请改用people.erase(people.begin() + 0);。您不能在 std::vector::erase 中提供密钥(例如在 std::set 中)。只接受迭代器。

标签: c++


【解决方案1】:

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

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

编辑: 擦除满足条件的元素:

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

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

第二种方式: 在person_id 类中创建新的operator==: 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);
}

【讨论】:

    【解决方案2】:

    这是&lt;vector&gt;erase函数原型:

    iterator erase (iterator position);
    

    您不能使用int 参数调用它。你需要一个vector::iterator。

    【讨论】:

      【解决方案3】:

      vector::erase 不知道数字 5 是指 ID=5 的人。您需要通过为该项目提供迭代器来告诉它。

      首先find您要通过搜索该条件删除的项目。

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

      然后,如果搜索成功,您可以擦除返回的迭代器。

      if (itr != people.end())
          people.erase(itr);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-23
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-18
        • 2014-11-29
        相关资源
        最近更新 更多