vector如何删除指定索引位置的元素

  1、remove并不是删除,仅仅是移除,要加上erase才能完成删除。
2、remove并不是删除指定位置的元素,而移除所有指定的元素。
3、用algorithm代替成员函数不是一个好的选择。

删除的方法:
vec.erase(remove(vec.begin(),vec.end(),value),vec.end());

例:ListBox的添加与删除
变量:
CListBox m_List;
vector<CString> m_str:

//Add:(如果存在则删除旧的)
int nlndex;
while ((nIndex = this->m_List.FindString(nIndex , ...)) != LB_ERR)
{
m_List.DeleteString( nIndex );
if((int)m_str.size()>=nIndex)
{
m_str.erase(remove(m_str.begin(),m_str.end(),m_str[nIndex]),m_str.end());
}
}

m_List.AddString(...);
m_str.push_back(...);


//delete:
int count = m_List.GetSelCount();
int* lpIndex = NULL;
if(count<0)
return;
if (count == 0)
m_List.ResetContent();
lpIndex = new int[count];
m_List.GetSelItems(count,lpIndex);
int num = 0;
for(int i = 0;i<count;i++)
{
int delNum = lpIndex[i];
if(delNum>=num &&num>0)
{
delNum = delNum-num;
}

if((int)m_str.size()>=delNum)
{
m_str.erase(remove(m_str.begin(),m_str.end(),m_str[delNum]),m_str.end());
}
m_List.DeleteString(delNum);
num++;
}
delete []lpIndex;




经验分享 程序员 微信小程序 职场和发展