入门经典紫书(刘汝佳)第五章例题汇总

结构体PointSum

#include<iostream>
using namespace std;

template <typename T>
struct Point{
     T x,y;
     Point(T x = 0, T y = 0):x(x),y(y) {}
};

template <typename T>
Point<T> operator + (const Point<T>& A, const Point<T>& B){
    return Point<T>(A.x+B.x,A.y+B.y);
}

template<typename T>
ostream& operator << (ostream &out,const Point<T>& p){
   out << "(" << p.x << "," << p.y <<")";
   return out;
}

template<typename T>
T sum(T* begin,T* end){
   T *p = begin;
   T ans = 0;
   for(T *p = begin ; p!= end ; p++)
     ans = ans + *p;
   return ans;
}

int main(){
   Point<int> a(1,2) , b(3,4);
   Point<double> c(1.1,2.2), d(3.3,4.4);
   cout << a+b << "  " << c+d << "\n";
   return 0;
}

 

 

 

lower_bound(C++)的使用方法SortAndlower_bound

#include<cstdio>
#include<algorithm>

using namespace std;
int a[10000];
int main(){
  int N=3;
  int x;
        for(int i = 0 ; i<N ; i++){
           scanf("%d",&a[i]);
        }
        sort(a,a+N);
           scanf("%d",&x);
           int *p = lower_bound(a,a+N,x);
           printf("大于等于%d的数为%d\n",x,*p);
           int w = lower_bound(a,a+N,x) - a;                       //注意:在这里返回的w的位置是指在数组中的下标,切记
           printf("大于等于%d的返回的位置为%d\n",x,w);
           return 0;

}
/*
     注意:1.lower_bound(&First,&end,int value)  传入起始位置,终止位置,查找的值
               返回:大于等于value值的第一个值的大小

               2.如果要返回位置,可以例如:int a[100];
               int p = lower_bound(a,a+n,x) - a;
*/

 

 

 

sumModel

#include<iostream>
using namespace std;

struct Point{
     int x,y;
     Point(int x = 0, int y = 0):x(x),y(y) {}
};

Point operator + (const Point& A, const Point& B){
    return Point(A.x+B.x,A.y+B.y);
}

ostream& operator << (ostream &out,const Point& p){
   out << "(" << p.x << "," << p.y <<")";
   return out;
}

template<typename T>
T sum(T* begin,T* end){
   T *p = begin;
   T ans = 0;
   for(T *p = begin ; p!= end ; p++)
     ans = ans + *p;
   return ans;
}

int main(){
   double a[] = {1.1,2.2,3.3,4.4};
   cout << sum(a,a+4) << "\n";
   Point b[] = { Point(1,2),Point(3,4),Point(5,6),Point(7,8)};
   cout << sum(b,b+4) << "\n";
   return 0;
}

 

 

 

TheBlocksProblemUVa101

 

 

与java中spilit相似的C语言strtok方法JavaSpilitAsCofStrtok

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值