C++Vector简单操作

来源:互联网 发布:淘宝上的优衣库代购 编辑:程序博客网 时间:2024/05/22 09:03

好像vector和QVector不太一样。

//iterator erase (const_iterator position);
//iterator erase (const_iterator first, const_iterator last);
//vector删除元素:
// An iterator pointing to the new location of the element that followed the last element erased by the function call. 
// This is the container end if the operation erased the last element in the sequence.
// Member type iterator is a random access iterator type that points to elements.

#include <QtCore/QCoreApplication>#include <qDebug>#include <vector>using namespace std;bool compare(const int &v1,const int &v2){return v1 < v2;}void print(vector<int> &vInt){qDebug()<<"size: "<<vInt.size();for(vector<int>::iterator it=vInt.begin(); it!=vInt.end(); ++it)qDebug()<<*it;}int main(int argc, char *argv[]){QCoreApplication a(argc, argv);vector<int> vInt;vInt.push_back(5);vInt.push_back(1);vInt.push_back(6);vInt.push_back(2);vInt.push_back(13);vInt.push_back(4);vInt.push_back(7);vInt.push_back(3);print(vInt);///删除某一元素for(vector<int>::iterator it=vInt.begin(); it!=vInt.end(); ){if(*it==13){it=vInt.erase(it);break;}else++it;}print(vInt);//排序操作sort(vInt.begin(),vInt.end(),compare);vInt.erase(vInt.begin(),vInt.begin()+3);print(vInt);return a.exec();}/*size:  8516213473size:  75162473size:  44567.....*/
erase返回一个指向最后一个被erase的元素的下一个元素指针。