使用了vector容器,remove_if(), for_each()等算法,并使用到了函数对象。
vector容器中存放的是多个字段的结构体,然后根据结构体的某个字段删除其在容器中的元素。
// 主要是用于练习使用STL中的泛型算法
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
/// 结构体
struct MyStruct
{
int nID;
string strName;
// string strDesc;
};
class CMyStructComp
{
private:
string m_strName;
public:
CMyStructComp(const string strName):m_strName(strName)
{}
bool operator()(const MyStruct &data)const
{
//if (m_strName == data.strName)
//{
// return true;
//}
//return false;
return (m_strName == data.strName)?true:false;
}
};
// 为减少string对象的构造及析构,使用字符串指针
class CMyStructComp2
{
private:
char* m_pName;
public:
CMyStructComp2(const char* pName)
{
m_pName = (char*) pName;
}
bool operator()(const MyStruct &data)const
{
if (!strcmp(m_pName, data.strName.c_str()))
{
return true;
}
return false;
}
};
void printMyStruct(const MyStruct &data)
{
std::cout <<"ID:"<< data.nID << ",Name:" << data.strName << std::endl;
}
std::vector<MyStruct > vecData;
void insertData()
{
MyStruct myData;
myData.nID = 1;
myData.strName = "aaaaa";
vecData.push_back(myData);
myData.nID = 2;
myData.strName = "bbbbb";
vecData.push_back(myData);
myData.nID = 3;
myData.strName = "CCCCC";
vecData.push_back(myData);
myData.nID = 4;
myData.strName = "ddddd";
vecData.push_back(myData);
myData.nID = 5;
myData.strName = "EEEEE";
vecData.push_back(myData);
}
int _tmain(int argc, _TCHAR* argv[])
{
insertData();
// 打印vector中所有的数据
for_each(vecData.begin(),vecData.end(),printMyStruct);
string strName("ddddd");
// 删除vector中符合条件的数据
vecData.erase(remove_if(vecData.begin(),vecData.end(),CMyStructComp(strName)),vecData.end());
std::cout <<"删除元素后:"<< std::endl ;
// 打印vector中所有的数据
for_each(vecData.begin(),vecData.end(),printMyStruct);
strName = "bbbbb";
// 删除vector中符合条件的数据
vecData.erase(remove_if(vecData.begin(),vecData.end(),CMyStructComp2(strName.c_str())),vecData.end());
std::cout <<"删除元素后:"<< std::endl ;
// 打印vector中所有的数据
for_each(vecData.begin(),vecData.end(),printMyStruct);
strName = "aaaaa";
// 删除vector中符合条件的数据
std::vector<MyStruct >::iterator itr;
itr = remove_if(vecData.begin(),vecData.end(),CMyStructComp2(strName.c_str()));
size_t nSize = 0;
size_t nCapacity = 0;
nSize = vecData.size();
nCapacity = vecData.capacity();
std::cout <<"remove_if删除元素后Size:"<< nSize << std::endl ;
std::cout <<"remove_if删除元素后Capacity:"<< nCapacity << std::endl ;
// 打印vector中所有的数据
for_each(vecData.begin(),vecData.end(),printMyStruct);
vecData.erase(itr);
std::cout <<"erase删除元素后Size:" << nSize << std::endl ;
std::cout <<"erase删除元素后Capacity:"<< nCapacity << std::endl ;
// 打印vector中所有的数据
for_each(vecData.begin(),vecData.end(),printMyStruct);
system("pause");
return 0;
}