C++ P P 16-4



#include "stdafx.h"
#include <iostream>
#include <vector>             //使用vector 模板类
#include <algorithm>      //使用sort()
#include <iterator>          //使用ostream_iterator模板
using namespace std;


int reduce(long ar[], int n);


int _tmain(int argc, _TCHAR* argv[])
{
long ar[] = { 4, 4, 6, 12, 2, 42, 5,12,6,88 };
int n = 10;
cout << "长度为10的数组元素为: ";
for (long x : ar)
cout << x << ' ' ;
cout << endl;
int x = reduce(ar, n);
cout << "剩余的元素个数: ";
cout << x << endl;


cin.get();
return 0;
}


int reduce(long ar[], int n)
{
ostream_iterator<long, char> out_iter(cout, " ");  //创建out_iter接口
vector<long> v1;                                                         //STL函数需要模板
int len = n;
while (n--)                                                                   //将数组元素复制到vector模板类中
v1.push_back(ar[n]);
//v1[len] = ar[len];                                               //直接会报异常,原因在于v1是空数组,而push.back可以动态改变数组
sort(v1.begin(), v1.end());                                        //排序
                                                                             //使用2个参数的sort(),需在定义能够处理该类型对象的operator<()函数
cout << "排序后: " ;
copy(v1.begin(), v1.end(), out_iter);                      //将v1容器发送到cout管理的输出流中(显示到控制台中)
cout << endl;


cout << "unique去除重复后: ";
unique(v1.begin(), v1.end());                               //去除重复的值
                                                                                  //实际是将相邻重复的值放到数组后面
                                                                                  //返回结果区间的结尾
copy(v1.begin(), v1.end(), out_iter);                   //将v1容器发送到cout管理的输出流中(显示到控制台中)
cout << endl;                                                          //看输出结果

cout << "erase去除重复后: ";
v1.erase(unique(v1.begin(), v1.end()) , v1.end()); //删除重复的元素
copy(v1.begin(), v1.end(), out_iter);                   //将v1容器发送到cout管理的输出流中(显示到控制台中)
cout << endl;
return v1.size();

}


///

//

v1.erase(unique(v1.begin(), v1.end()) , v1.end());

得不到正确的效果,原因还不知道0-0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值