C++泛型编程中算法库<algorithm>和向量<vector>的简单实例

本文通过实例演示了C++中如何使用algorithm库的max_element、min_element、count、find、unique、sort、binary_search、remove和replace等函数,结合vector容器进行操作,包括查找最大最小值、计数、排序、二分查找、删除和替换元素等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void main(void)
{
 const int size = 10 ;
 vector<int> v(size);        //说明容器v,其大小为size
 vector<int>::iterator start, end, it, pos ;  //说明4个泛型指针,即迭代子(迭代器)
 int a[size]={54,10,10,303,303,54,54,54,54,10};
 //以a数组各元素值初始化容器v
 for(int i = 0; i<size; i++)       
  v[i]=a[i];
 start = v.begin() ;          //首元素位置
 end = v.end() ;          //末元素位置
 cout<<"v={ " ;         
 //显示出v中各元素
 for(it = start; it != end; it++)
  cout << *it << " " ;
 cout<<" }"<<endl ;
 pos = max_element(start, end) ;    //v中第一个最大元素
 cout << "The maximum element in v is: " << *pos << endl ;
 //从第一个最大元素往后的所有元素
 for(it = pos; it != end; it++)     
  cout << *it << " " ;
 cout<<endl ;
 pos = min_element(start, end) ;    //v中第一个最小元素
 cout << "The minimum element in v is: " << *pos << endl ;
 //从第一个最小元素往后的所有元素
 for(it = pos; it != end; it++)      
  cout << *it << " " ;
 cout<<endl ;
 cout<<"count(start, end, 10)= ";
 cout<<count(start, end, 10)<<endl;  //查找对象10所出现的次数
 pos = find(start, end, 303);      //查找对象303的首次出现(位置)
 cout << "After 'find(start, end, 303)', *pos= " << *pos << endl ; 
 //从第一个303往后的所有元素
 for(it = pos; it != end; it++)   
  cout << *it << " " ;
 cout<<endl ;
 pos = unique(start, end) ;      //使具有连续相同值的对象只留下一份
 cout << "After 'unique', *pos= " << *pos << endl ;
 for(it = start; it != pos; it++)      //unique操作后的对象序列
  cout << *it << " " ;
 cout<<endl ;
 sort(start, pos);          //排序
 cout << "After 'sort(start, pos);' "<< endl ;
 for(it = start; it != pos; it++)      //排序后的结果序列
  cout << *it << " " ;
 cout<<endl;
 cout<<"binary_search(start, end, 54)=>";
 cout<<binary_search(start, end, 54);  //二分查找对象54是否出现
 cout<<endl ;
 pos = remove(start, pos, 10);    //移去所有的10
 cout << "After 'remove(start, pos, 10);' "<<endl ;
 for(it = start; it != pos; it++)      //移去所有10之后的序列
  cout << *it << " " ;
 cout<<endl ;
 replace(start, pos, 54, 888);      //将所有的54替换为888
 cout << "After 'replace(start, pos, 54, 888);' "<<endl ;
 for(it = start; it != pos; it++)      //替换之后的序列
  cout << *it << " " ;
 cout<<endl ;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值