C++ vector 多次删除第一个元素

转载声明:  代码都是来源于一下连接,做了一点点修改,为了记忆方便,故贴在这里,原文链接:
http://blog.csdn.net/doctor_feng/article/details/11880787 ////test cpp operation
//
//#include<vector>
//#include<stdio.h>
//using namespace std;
//typedef struct {
// int id;
// int name;
//}Student;
//
//
//
//int main() {
// Student ss = {12,13};
// printf("%d %d\n", ss.id, ss.name);
// vector<Student> st;
// //struct 初始化
// vector<Student> s(2,{12,13}) ; // s(2, ss);
// s.push_back(ss);
//
//
//
// int i = 1;
//
// while(i < 10) {
// printf("%d, %d", s.front().id, s.front().name);
//
// i++;
// }
//} #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <list>
using namespace std; voidPrintInt(const int&nData)
{
cout<<nData<<endl;
}
int main()
{
vector<int> vecInt;
for(int i=0; i<10;++i)
{
vecInt.push_back(i);
}
cout<<"向量中的内容为:"<<endl;
//for_each(vecInt.begin(),vecInt.end(),PrintInt);
for(vector<int>::iterator iter = vecInt.begin(); iter != vecInt.end(); ++iter) {
cout << *iter << " ";
}
cout << "\n";
cout<<"vector contains "<<vecInt.size()<<" elements"<<endl;
vecInt.pop_back();//删除最后一个元素
cout<<"删除最后一个元素后,vector contains "<<vecInt.size()<<" elements"<<endl; vector<int>::iterator k = vecInt.begin();
vecInt.erase(k);//删除第一个元素 for(vector<int>::iterator iter = vecInt.begin(); iter != vecInt.end(); ++iter) {
cout << *iter << " ";
}
cout << "\n"; //vecInt.erase(k); //迭代器k已经失效,会出错
cout<<"删除第一个元素后,vector contains "<<vecInt.size()<<" elements"<<endl;
k = vecInt.begin();
vecInt.erase(k); for(vector<int>::iterator iter = vecInt.begin(); iter != vecInt.end(); ++iter) {
cout << *iter << " ";
}
cout << "\n"; cout<<"删除第一个元素后,vector contains "<<vecInt.size()<<" elements"<<endl;
//vecInt.erase(vecInt.begin(),vecInt.end()); //删除所有元素
//cout<<"删除所有元素后,vector contains "<<vecInt.size()<<"elements"<<endl; //输出为0
vector<int>::iterator vecNewEnd =remove(vecInt.begin(),vecInt.end(),5); //删除元素
cout<<"删除元素后,vector contains "<<vecInt.size()<<" elements"<<endl;
cout<<"向量开始到新结束为止的元素:"<<endl;
//for_each(vecInt.begin(),vecNewEnd,PrintInt);
cout<<"向量中的元素:"<<endl;
//for_each(vecInt.begin(),vecInt.end(),PrintInt); return 0;
}

  

上一篇:mysql Last_SQL_Errno: 1197 Coordinator stopped because there were error(s) in the worker(s)问题处理


下一篇:jQuery 插件开发指南