建立一个数据结构来包含这些数据,类似代码如下:
#include
enum findmodes {
FM_INVALID = 0,
FM_IS,
FM_STARTSWITH,
FM_ENDSWITH,
FM_CONTAINS
};
typedef struct tagFindStr {
UINT iMode;
CString szMatchStr;
} FindStr;
typedef FindStr* LPFINDSTR;
然后处理条件判断:
class FindMatchingString : public std::unary_function {
public:
FindMatchingString(const LPFINDSTR lpFS) :
m_lpFS(lpFS) {}
bool operator()(CString& szStringToCompare) const {
bool retVal = false;
switch (m_lpFS->iMode) {
case FM_IS: {
retVal = (szStringToCompare == m_lpFDD->szMatchStr);
break;
}
case FM_STARTSWITH: {
retVal = (szStringToCompare.Left(m_lpFDD->szMatchStr.GetLength())
== m_lpFDD->szWindowTitle);
break;
}
case FM_ENDSWITH: {
retVal = (szStringToCompare.Right(m_lpFDD->szMatchStr.GetLength())
== m_lpFDD->szMatchStr);
break;
}
case FM_CONTAINS: {
retVal = (szStringToCompare.Find(m_lpFDD->szMatchStr) != -1);
break;
}
}
return retVal;
}
private:
LPFINDSTR m_lpFS;
};
通过这个操作你可以从vector中有效地删除数据:
FindStr fs;
fs.iMode = FM_CONTAINS;
fs.szMatchStr = szRemove;
vs.erase(std::remove_if(vs.begin(), vs.end(), FindMatchingString(&fs)), vs.end());
Remove(),remove_if()等所有的移出操作都是建立在一个迭代范围上的,不能操作容器中的数据。
所以在使用remove_if(),实际上操作的时容器里数据的上面的。
看到remove_if()实际上是根据条件对迭代地址进行了修改,在数据的后面存在一些残余的数据,
那些需要删除的数据。剩下的数据的位置可能不是原来的数据,但他们是不知道的。
调用erase()来删除那些残余的数据。
注意上面例子中通过erase()删除remove_if()的结果和vs.enc()范围的数据。
?
7. 综合例子:
?
//---------------------------------------------------------------------------
#include
#pragma hdrstop
#include Unit1.h
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource *.dfm
TForm1 *Form1;
#include
#include
using namespace std;
struct STResult
{
double Time;
double Xp;
double Yp;
int id;
};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
vector ResultVector;
void __fastcall test()
{
//test
//vector ResultVector;
STResult stritem;
stritem.Time = .1;
stritem.Xp = .1;
stritem.Yp = .1;
stritem.id = 1;
ResultVector.push_back( stritem );
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
test();
assert(ResultVector[0].id == 1);
}
?
?