STL中vector的赋值,遍历,查找,删除,自定义排序——sort,push_back,find,erase

   今天学习网络编程,那个程序中利用了STL中的sort,push_back,erase,自己没有接触过,今天学习一下,写了一个简单的学习程序。编译环境是VC6.0
         这个程序使用了vector的两种赋值方式,遍历,查找,删除,自定义排序。希望对看到此文的同学有所帮助。
        另外,一定要引如using namespace std; 否则后面老是要写std::vector<int> 很麻烦的。
        assert.h不是必须的,这里只不过用了一下而已,它是和assert()函数的头文件。
         algorithm头文件不可少,因为sort,find这两个函数实在这个头文件中。

#include <vector>
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
//把 vector<int>定义成这个 INTVECTOR 为了后面写着方便
typedef vector<int> INTVECTOR;

//排序函数按降序输出
bool cmp(int a, int b)
{
return a < b;
}


int main()
{

int a[6] = {1, 5, 3, 8, 0, -1};
//给vector<int>赋值,方法一
//INTVECTOR vi(a, a + sizeof(a)/sizeof(int));//sizeof(a)/sizeof(int)求数组的大小

//给vector<int>赋值,方法二
INTVECTOR vi;
for (int i = 0; i < 6; i++)
   vi.push_back(a[i]);

//遍历
cout << "遍历" << endl;
INTVECTOR::iterator ite;
for (ite = vi.begin(); ite != vi.end(); ite++)
{
   cout << *ite << " ";
}
cout << endl;

//查找,find函数需要引入#include <algorithm>
cout << "查找5" << endl;
ite = find(vi.begin() , vi.end(), 5); 
assert(ite != vi.end());

//删除
cout << "删除" << *ite << endl ; //返回容器内找到值的位置。
vi.erase(ite);

cout << "删除后遍历" << endl;
for (ite = vi.begin(); ite != vi.end(); ite++)
{
   cout << *ite << " ";
}
cout << endl;

//排序,sort函数需要引入#include <algorithm>
//sort函数有两种写法,一种是默认升序,
//另外一种需要定义一个cmp函数。
cout << "排序" <<endl;
sort(vi.begin(), vi.end(), cmp);
for (ite = vi.begin(); ite != vi.end(); ite++)
{
   cout << *ite << " ";
}
cout << endl;

//如果想定义比较复杂的cmp请参考
//http://hi.baidu.com/topman3758/blog/item/859b18da6222623933fa1cd8.html
return 0;
}

假设自己定义了一个结构体node
struct node{
    int a;
    int b;
    double c;
}
   有一个node类型的数组node arr[100],想对它进行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写这样一个比较函数:

以下是代码片段:
bool cmp(node x,node y)
{
     if(x.a!=y.a) return x.a

if(x.b!=y.b) return x.b>y.b;
     return return x.c>y.c;
}     排序时写sort(arr,a+100,cmp);

    最后看一个完整的实例,初赛时的一道题目“文件名排序 ”。

以下是代码片段:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
//定义一个结构体来表示文件,a代表文件名,b代表文件类型(要么"File"要么"Dir")
struct node{
string a,b;
};
//ASCII码中,所有大写字母排在所有小写字母前面,'A'<'Z'<'a'<'z'
//而这题要求忽略大小写,所以不能直接用字符串的比较。自定义了一个lt函数,就是less than的意思
//先把两个字符串全部转化为小写,再比较大小(字典序)
bool lt(string x,string y)
{
int i;
for(i=0;i<x.length();i++)
if(x[i]>='A'&&x[i]<='Z')
   x[i]='a'+(x[i]-'A');
for(i=0;i<y.length();i++)
if(y[i]>='A'&&y[i]<='Z')
   y[i]='a'+(y[i]-'A');
return x<y; 
}
//自定义的比较函数,先按b值升序排列(也就是"Dir"排在"File"前面)
//如果b值相同,再按a升序排列,用的是刚才定义的lt函数
bool comp(node x,node y)
{
if(x.b!=y.b)return x.b<y.b;
return lt(x.a,y.a);
}
int main()
{
node arr[10001];
int size=0;
while(cin>>arr[size].a>>arr[size].b)
size++;
sort(arr,arr+size,comp);
for(int i=0;i<size;i++)
cout<<arr[i].a<<" "<<arr[i].b<<endl;
return 0;
}

原地址:http://hi.baidu.com/ozwarld/item/68656be6ae00663f4ddcaf87

原文地址:https://www.cnblogs.com/lanye/p/3660356.html