删除vector数组中指定元素

比如删除第4个元素:

 

vector<int> v;

v.erase(v.begin()+3);

 

v.erase()的参数是一个iterator,它没有一个参数为int的版本,所以你需要指定一个iterator给它, 就像上面的v.begin()+3就是指第4个元素。

 

-------------------------------------------------------------------------

 

这里是msdn的实例代码

C/C++ code#include
#include

#if _MSC_VER > 1020   // if VC++ version is > 4.2
   using namespace std;  // std c++ libs implemented in std
   #endif

typedef vector > INTVECTOR;

const ARRAY_SIZE = 10;

void ShowVector(INTVECTOR &theVector);

void main()
{
    // Dynamically allocated vector begins with 0 elements.
    INTVECTOR theVector;

    // Intialize the vector to contain the numbers 0-9.
    for (int cEachItem = 0; cEachItem < ARRAY_SIZE; cEachItem++)
        theVector.push_back(cEachItem);

    // Output the contents of the dynamic vector of integers.
    ShowVector(theVector);

    // Using void iterator erase(iterator Iterator) to
    // delete the 6th element (Index starts with 0).
    theVector.erase(theVector.begin() + 5);

    // Output the contents of the dynamic vector of integers.
    ShowVector(theVector);

    // Using iterator erase(iterator First, iterator Last) to
    // delete a range of elements all at once.
    theVector.erase(theVector.begin(), theVector.end());

    // Show what's left (actually, nothing).
    ShowVector(theVector);
}

// Output the contents of the dynamic vector or display a
// message if the vector is empty.
void ShowVector(INTVECTOR &theVector)
{
    // First see if there's anything in the vector. Quit if so.
    if (theVector.empty())
    {
        cout << endl << "theVector is empty." << endl;
        return;
    }

    // Iterator is used to loop through the vector.
    INTVECTOR::iterator theIterator;

    // Output contents of theVector.
    cout << endl << "theVector [ " ;
    for (theIterator = theVector.begin(); theIterator != theVector.end();
         theIterator++)
    {
        cout << *theIterator;
        if (theIterator != theVector.end()-1) cout << ", ";
                                              // cosmetics for the output
    }
    cout << " ]" << endl ;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值