c++ - 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;
}
解决方案
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);
}
推荐阅读
- c# - 蛋糕自定义 MsBuild 路径
- c# - 为上传文件添加计数器 C#
- c# - 如何在 VS Code 中更改 .NET SDK 语言
- c# - 将 ComboboxItem 作为复选框绑定到它在列表中的存在?
- javascript - 如何更改 Mapbox Geocoder 搜索栏的大小?
- html - 在ios safari上定位固定元素?
- python - Scrapy:无法创建项目
- javascript - clearInterval 执行后刷新页面
- kotlin - BufferedImage drawString 损坏的字母
- c# - 从 C# 中的 .txt 文件中的单行获取多个子字符串