c++ vector 使用方法

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
/****数组用法****/
int iar[6] = {-12,-2,0,8,5,4};
vector<int> ivec(10,3);
vector<int> ivec1(iar+1,iar+4);
vector<int> ivec2(ivec1);

vector<int>::iterator it = ivec1.begin();
for(int ix = 0; ix < ivec1.size();)
{
cout<<ivec1[ix]<<endl;
if(ivec1[ix] == 0)
{
it += ix;
ivec1.erase(it);
it = ivec1.begin();
}
else
{
ix++;
}
}

for(int ix = 0; ix < ivec1.size();ix++)
{
cout<<ivec1[ix]<<endl;
}

/****STL用法****/

vector<string> ivec3;
ivec3.push_back("w1");
ivec3.push_back("w2");
ivec3.push_back("w3");
for(vector<string>::iterator it = ivec3.begin(); it < ivec3.end();)
{
cout<<*it<<endl;
////字符串判等 第一种方式
//if(*it == "w3")
//{
// cout<<"*it == \"s3\""<<endl;
// it++;
//}
//字符串判等 第二种方式
if(strcmp(it->c_str(), "w3") == 0)
{
cout<<"strcmp(it->c_str(),\"w3\")"<<endl;
int si = it - ivec3.begin();
ivec3.erase(it);//erase掉it以后,it无法访问,需要重新设置it
it = ivec3.begin() + si;
}
else
{
it++;
}
}

for(vector<string>::iterator it = ivec3.begin(); it != ivec3.end();it++)
{
cout<<*it<<endl;
}
}
posted @ 2011-10-25 13:43  韩冬冬  阅读(526)  评论(0编辑  收藏  举报