C++primer plus第六版课后编程题答案16.5

main155.cpp

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
static void output(const long &l){
	std::cout<<l<<"  ";
}
template <class T>
static int reduce(T ar[],int n)
{
	std::vector<T> arr;
	int len=n;
	while(len--)
	{
		arr.push_back(ar[len]);//将数组复制过去
	}
	sort(arr.begin(),arr.end());
	//std::for_each(arr.begin(),arr.end(),output);//测试排序是否成功

	std::cout<<std::endl;
	
	T temp=arr[0];//中间值
	T pos=arr[0];
	
	len=n;
	ar[0]=temp;//先置ar[0]
	int count=1;//ar的下标值
	int i=1;//arr的下标值
	std::cout<<"ar[0]="<<ar[0]<<std::endl;
	while(i<len+1)//(len)//将arr的值去掉重复后,复制到ar//自己调试一下,看看条件为什么是这个
	{
		if(temp!=pos)
		{
			ar[count]=pos;//为了这里ar永远只有一个元素?
			std::cout<<"ar["<<count<<"]="<<ar[count]<<std::endl;
			count++;
			temp=pos;//原来是我把数组长度弄错了,导致了上面的问题
		}
		if(i==len)
			break;
		pos=arr[i];
		i++;
		//len--;
	}
	//count++;
 	ar[count]='\0';//截断数组
	
	std::cout<<std::endl;
	//for(int k=0;k<count;k++)
		//std::cout<<ar[k]<<" ";
		
	return count;

};

void main165()
{
	using std::cout;
	using std::endl;
	using std::cin;
	long ar1[10]={
		10,12,9,5,6,
		9,5,9,7,150
	};
	long ar2[8]={
		1,5,6,8,
		5,6,1,3
	};

	std::string str[10]={
		"add","hehe","hehe","abrot","zhen",
		"coco","coci","cocoy","abrot","yes"
	};

	int len=reduce(ar2,8);
	cout<<"\nNow is :"<<endl;
	for(int i=0;i<len;i++)
		cout<<ar2[i]<<"  ";

	int lenstr=reduce(str,10);
	for(int i=0;i<lenstr;i++)
		cout<<str[i]<<endl;

	cin.get();






}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值