您的位置:首页 > 其它

删除vector数组中指定元素

2009-09-11 16:33 519 查看
比如删除第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 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: