82 篇文章 1 订阅

# STL vector的erase操作问题

vector<unsigned short> m_UintVector;

m_UintVector.push_back(10);

m_UintVector.push_back(20);

m_UintVector.push_back(30);

vector<unsigned short>::iterator itr;

itr = std::find(m_UintVector.begin(), m_UintVector.end(), 20);

m_UintVector.erase( itr);

vector<unsigned short> m_UintVector;

m_UintVector.push_back(10);

m_UintVector.push_back(20);

m_UintVector.push_back(30);

vector<unsigned short>::iterator itr;

itr = std::find(m_UintVector.begin(), m_UintVector.end(), 20);

//删除元素

int diff = itr - m_UintVector.begin();

m_UintVector.erase(  m_UintVector.begin() + diff );

void main()

{

vector<int> member;

member.push_back(1);

member.push_back(2);

member.push_back(2);

member.push_back(3);

member.push_back(1);

member.push_back(2);

member.push_back(4);

vector<int>::iterator iter;

for(iter = member.begin();

iter != member.end();iter++)

cout<<*iter<<endl;

cout<<"do erase--------"<<endl;

for(iter = member.begin();

iter != member.end();iter++)

{

if(*iter == 2)

{

member.erase(iter);

}

}

for(iter = member.begin();

iter != member.end();iter++)

cout<<*iter<<endl;

}

iterator erase ( iterator position );

iterator erase ( iterator first, iterator last );

for(iter = member.begin(); iter != member.end();)

{

if(*iter == 2)

{

iter = member.erase(iter);

}

else

{

iter++;

}

}

// Compile OK, but run-time error!!

// for(std::vector<int>::iterator iter = ivec.begin();

//  iter != ivec.end(); ++iter) {

//    if (*iter == 8) {

//      ivec.erase(iter);

//    }

// }

// This is a RIGHT way to do it.

std::vector<int>::iterator iter = find(ivec.begin(), ivec.end(), 8);

if (iter != ivec.end()) {

ivec.erase(iter);

}

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
07-29 9859
04-16 8031
11-14 1019
08-28 282
02-09

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。