我采用的方法是利用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;
}