1. 程式人生 > >使用find_if的自定義條件查詢vector或map

使用find_if的自定義條件查詢vector或map


#include<algorithm>
using namespace std;
vector<testStruct>testStructVector;

void CtestDlg::OnBnClickedButton1()
{
	testStruct struct1;
	for(int i = 0; i < 5; i++)
	{
		struct1.a = i;
		struct1.b = i + i;
		testStructVector.push_back(struct1);
	}


	auto itrFind = find_if(testStructVector.begin(), testStructVector.end(), [](testStruct myStruct)
	{
		return myStruct.a > 2 && myStruct.b < 8;
	});


	if(itrFind != testStructVector.end())
		TRACE("found!");
	else
		TRACE("not found!");
}

結果:
struct1.a = 0,1,2,3,4
struct1.b = 0,2,4,6,8
條件
myStruct.a > 2 && myStruct.b < 8能找到struct1.a = 3, myStruct.b =6時的值,因此是found