使用vector进行排序插入
如果我们有个vector容器,如std::vector vMyVec,里面现在已经有1,3,5,7, 四个元素,现在需要往1,3之间插入2这个元素,那怎么办呢,更或者vector里面是个自定义的类型,需要做这种插入操作,那可以采用下面的方法 #include "stdafx.h"#include#includeclass CEntity{public:CEntity(
·
如果我们有个vector容器,如std::vector<int> vMyVec,里面现在已经有1,3,5,7, 四个元素,现在需要往1,3之间插入2这个元素,那怎么办呢,更或者vector里面是个自定义的类型,需要做这种插入操作,那可以采用下面的方法
#include "stdafx.h"
#include <vector>
#include <algorithm>
class CEntity
{
public:
CEntity( int nValue=0 ):m_nValue(nValue)
{
}
int m_nValue;
};
class CLess
{
public:
bool operator()( const CEntity& lh, const CEntity& rh )
{
//这里还可以进行一些自定义的判断方式
return lh.m_nValue < rh.m_nValue;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<CEntity> vEntity1;
std::vector<CEntity> vEntity2;
for ( int n=0; n<10; n++ )
{
nValue = rand()%10;
vEntity1.insert(std::upper_bound(vEntity1.begin(),vEntity1.end(),CEntity(nValue),CLess()), CEntity(nValue) );
vEntity2.push_back( CEntity(nValue) );
}
}
更多推荐
所有评论(0)