设为首页 加入收藏

TOP

C++中vector使用(二)
2015-11-21 00:58:34 来源: 作者: 【 】 浏览:6
Tags:vector 使用
建立一个数据结构来包含这些数据,类似代码如下:
#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);
}


?

?

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LeetCode15:3Sum 下一篇[c++]通过一个简单的程序引出#def..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: