返回> 网站首页 

[原创]STL标准模板库 - 搜索、最小值、条件删除

yoours2011-06-28 15:51:11 阅读 1166

简介一边听听音乐,一边写写文章。

一、 回调函数
// 搜索的回调函数 返回搜索结果
bool VideoFun(const vector<VideoFile*>::value_type &value)
{
bool bRet = false;

if (channelParam == NULL || strcmp(value->Channel, channelParam) == 0)
bRet = true;
else
return false;

if (timeParam == NULL || strcmp(value->Time, timeParam) == 0)
bRet = true;
else
return false;

if (pathParam == NULL || strcmp(value->Path, pathParam) == 0)
bRet = true;
else
return false;

return bRet;
}

// 最小值的回调函数 返回最小值
bool min_comp(const vector<VideoFile*>::value_type &value1, const vector<VideoFile*>::value_type &value2)
{
char* time1 = new char[9];
memset(time1, 0, 9);
memcpy(time1, value1->Time, 8);
int iTime1 = atoi(time1);
delete[] time1;
time1 = NULL;

char* time2 = new char[9];
memset(time2, 0, 9);
memcpy(time2, value2->Time, 8);
int iTime2 = atoi(time2);
delete[] time2;
time2 = NULL;

return (iTime1 < iTime2);
}

// 条件删除回调函数 返回iterator
bool del_if(vector<VideoFile*>::value_type &value)
{
if (strcmp(value->Channel, channelParam) == 0)
{
delete value->Channel;
value->Channel = NULL;

delete value->Time;
value->Time = NULL;

DeleteFile(value->Path);
delete[] value->Path;
value->Path = NULL;

delete value;
value = NULL;
return true;
}else{
return false;
}
}

二、使用方法
// 搜索 使用回调函数
vector<VideoFile*>::iterator it = find_if(videoFileList.begin(), videoFileList.end(), VideoFun);
if (it != videoFileList.end())
{
//第一个满足条件的元素
}

while (it != videoFileList.end())
{
it++;//让it指想满足条件的元素的下一个元素,即,再次搜索时从满足条件的元素的下一个位置开始
it = find_if(it, videoFileList.end(), VideoFun);
if (it != videoFileList.end())
{
//再次找到的符合要求的元素
}
}


// 查找最小值 使用回调函数
it = min_element(videoFileList.begin(), videoFileList.end(), min_comp);
if (it != videoFileList.end())
{
//满足条件的元素
}


// 删除符合条件的项 使用回调函数
videoFileList.erase(remove_if(videoFileList.begin(), videoFileList.end(), del_if), videoFileList.end());

微信小程序扫码登陆

文章评论

1166人参与,0条评论