如何在“元素为自定义类型的vector”中查找指定的元素?

来源:互联网 发布:凯里欧文生涯数据 编辑:程序博客网 时间:2024/06/06 00:13

我采用的方法是利用STL中提供的find方法,关键是在定义类型中重载“==”操作符

代码示例:

/ vecfind.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;


//自定义类型
class  MYSTRUCT
{
public:
int id;
int nums;
vector<int> vec;


MYSTRUCT()
{
nums=0;
vec.resize(0);
}


bool operator==( const MYSTRUCT& objstruct) const  //重载“==”操作符
{
return objstruct.id==id;//具体匹配条件自己设定,可以设定多个
}

};


int _tmain(int argc, _TCHAR* argv[])
{
vector<MYSTRUCT> structs;

for(int i=0;i<5;i++)
{
MYSTRUCT myStruct;
myStruct.id=i;
myStruct.nums=i;
structs.push_back(myStruct);
}


MYSTRUCT temStruct;
temStruct.id=2;


vector<MYSTRUCT>::iterator it;

it=find(structs.begin(),structs.end(),temStruct);


if(it!=structs.end())
{
cout<<it->nums<<endl;
}
else
{
cout<<"NO"<<endl;
}


return 0;
}

原创粉丝点击