C++查找Vector中自定义的结构体中的数据中的内容find()
自定义的结构体
typedef struct CollectionLevel_s
{
int collectionPos;
int level;
}CollectionLevel_t;
typedef struct CollectionLevelCount_s
{
CollectionLevel_t CollectionLevel;
int count;
bool operator == (const CollectionLevel_t& e) {
return (this->CollectionLevel.collectionPos == e.collectionPos) && (this->CollectionLevel.level == e.level);
}
bool operator == (const int& pos) {
return (this->CollectionLevel.collectionPos == pos);
}
}CollectionLevelCount_t;
使用函数查找
使用函数查找的时候,必须重载操作符才可以。
查找容器中的CollectionLevelCount_s中的CollectionLevel数据是否相等。
需要重载操作符
bool operator == (const CollectionLevel_t& e) {
return (this->CollectionLevel.collectionPos == e.collectionPos) && (this->CollectionLevel.level == e.level);
}
CollectionLevelCount_t data;
data.count=0;
data.CollectionLevel.collectionPos=10;
data.CollectionLevel.level=1;
std::vector<CollectionLevelCount_t>ve_collectionLevelCount;
auto tmp = find(ve_collectionLevelCount.begin(), ve_collectionLevelCount.end(),data);
if (tmp == ve_collectionLevelCount.end())
{
//没有找到数据
}
else
{
//找到了数据
}
查找容器中的CollectionLevelCount_s中的CollectionLevel数据中的collectionPos数据是否相等。
需要重载操作符
bool operator == (const int& pos) {
return (this->CollectionLevel.collectionPos == pos);
}
例子:
//自己准备数据
auto tmp = find(ve_collectionLevelCount.begin(), ve_collectionLevelCount.end(), elem1.collectionPos);
if (tmp == ve_collectionLevelCount.end())
{
//查找到对应的collectionPos对应相等的数据了
}
else
{
//没有找到数据
}
C++中自定义结构体在Vector中的查找操作
这篇博客介绍了如何在C++中使用自定义结构体`CollectionLevelCount_s`的`std::vector`中进行查找操作。通过重载`operator==`来比较结构体中的`CollectionLevel`数据及`collectionPos`字段。示例展示了如何查找结构体完全匹配以及仅`collectionPos`匹配的情况,并提供了相应的代码实现。
2万+

被折叠的 条评论
为什么被折叠?



