C++中vector使用find函数查找struct结构体内容
发布日期:2021-05-28 16:52:30 浏览次数:31 分类:精选文章

本文共 1312 字,大约阅读时间需要 4 分钟。

vector中使用find函数查找结构体内容

1. 基本类型的查找

在C++中,vector可以用find函数查找基本类型的元素。例如,标准的数值类型如int、string等,可以直接应用find函数。以下是一个简单示例:

#include 
#include
using namespace std;int main() { vector
arr; arr.push_back(1); arr.push_back(3); arr.push_back(7); arr.push_back(2); int x = 7; vector
::iterator it = find(arr.begin(), arr.end(), x); if (it != arr.end()) { cout << "Find!" << endl; } else { cout << "Not find!" << endl; }}

2. 复杂类型的查找(如结构体)

使用find函数直接查找结构体在vector中的元素会导致错误,原因在于find函数只能比较基于内建类型的元素。在这种情况下,我们需要手动重载非静态成员函数,或者使用更高级的方法如使用二进制搜索等。

下面是一个使用特定比较操作符实现结构体查找的示例:

#include 
#include
using namespace std;struct edge_str { bool operator==(const edge_str& other) { return (this->posx == other.posx) && (this->posy == other.posy); } bool operator==(const int& pos) { return this->posx == pos; }};int main() { vector
arr; edge_str x = {5, 7}; auto it = find(arr.begin(), arr.end(), x); if (it != arr.end()) { cout << "Find!" << endl; } else { cout << "Not find!" << endl; }}

在这一示例中,edge_str结构体定义了两个比较运算符:一个用于比较两个边的位置坐标,另一个用于比较位置坐标与整数值。这允许find函数理解如何比较边和整数,从而实现查找功能。

请注意,在结构体的比较中,需要注意定义全局operator==,或者在命名空间中声明。这确保find函数能够正确识别和使用自定义的比较逻辑。

上一篇:C++11产生随机数
下一篇:Clion安装配置(Windows)

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月28日 14时57分00秒